Swift 使用委托创建 class

Swift create a class using a delegate

这可能在某个地方被谈论过,但我找不到任何谈论这个的文章。我正在尝试编写一个 class 来环绕苹果的原生 CoreLocation API。我的目标是能够从 locationManager 委托中调用 LocationTrack.getDPS 之类的东西并获得 return gps 坐标。

class LocationTrack: CLLocationManagerDelegate  {

    if (CLLocationManager.locationServicesEnabled())
            {
                locationManager = CLLocationManager()
                locationManager.delegate = self
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.requestAlwaysAuthorization()
                locationManager.startUpdatingLocation()
            }
        }

  func getDPS(completion: @escaping (result: [CLLocation]) -> () {

       //How to get below delegate response into this function?

    }

  func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

      print(locations)

}


    }

定义 属性 以捕获您的完成处理程序:

private var handler: (([CLLocation]) -> Void)?

getDPS保存并开始更新位置:

func getDPS(_ completion: @escaping ([CLLocation]) -> Void) {
    handler = completion
    locationManager.startUpdatingLocation()
}

然后你的 didUpdateLocations 可以调用那个闭包:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    handler?(locations)
    handler = nil
    locationManager.stopUpdatingLocation()
}

将所有这些放在一起,可能是这样的:

class LocationTrack: NSObject {
    private lazy var locationManager: CLLocationManager = {
        let locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()   // perhaps `requestWhenInUseAuthorization` is better?
        return locationManager
    }()

    private var handler: (([CLLocation]) -> Void)?

    func getDPS(_ completion: @escaping ([CLLocation]) -> Void) {
        handler = completion
        locationManager.startUpdatingLocation()
    }
}

extension LocationTrack: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        handler?(locations)
        handler = nil
        locationManager.stopUpdatingLocation()
    }
}

很明显,您可以添加自己的错误处理以及您有什么,但希望这说明了将闭包保存在 属性 中并在您收到委托回调时调用它的想法。