Swift使用委托创建类

时间:2019-03-21 23:52:20

标签: swift core-location

这可能是在某处谈论的,但是我找不到任何有关此的文章。我正在尝试编写一个包装苹果本地CoreLocation API的类。我的目标是能够调用诸如LocationTrack.getDPS之类的东西,并从locationManager委托中返回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)

}


    }

1 个答案:

答案 0 :(得分:1)

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

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()
    }
}

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

相关问题