首页 > 解决方案 > 实现定位协议

问题描述

我喜欢面向协议编程的概念,我正在尝试通过协议扩展快速开始编写协议。

我正在尝试使用协议扩展来获取设备位置。

但是,我在创建它时遇到了以下问题:

import Foundation
import CoreLocation

protocol Locator:CLLocationManagerDelegate {
var locationManager:CLLocationManager!
{ get set }

var locationHandler: ((CLLocation)->())?
{ get set }

func getLocation(completionHandler:@escaping (CLLocation)->())
}

extension Locator {

    private var _locationManager:CLLocationManager {
        get {return self.locationManager} set {self.locationManager = newValue}
    }

    private var _locationHandler:((CLLocation)->())? {
        get {return self.locationHandler} set {self.locationHandler = newValue}
    }

    func getLocation(completionHandler:@escaping (CLLocation)->()) {
        self.locationManager = CLLocationManager()
        self.locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
        let status = CLLocationManager.authorizationStatus()
        switch status {
        case .notDetermined:
            self.locationManager.requestAlwaysAuthorization()
            return
        case .denied, .restricted:
            return
        case .authorizedAlways, .authorizedWhenInUse:
            self.locationManager.startUpdatingLocation()
        @unknown default:
            break
        }
        self.locationHandler = completionHandler

    }

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways  {
            self.locationManager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        print("Hey this is a location")
        if let currentLocation = locations.last {
            self._locationHandler?(currentLocation)
        }
    }


}

但是,完成处理程序无法正常工作。

我的问题是什么,我该如何继续在协议概念中创建它。

标签: swiftswift-protocols

解决方案


推荐阅读