Swift使用委托创建一个类

问题描述 投票:1回答:1

这可能会在某个地方讨论,但我找不到任何谈论这个的文章。我正在尝试编写一个包含苹果本机CoreLocation API的类。我的目标是能够从locationManager委托调用像LocationTrack.getDPS这样的东西并返回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)

}


    }
swift core-location
1个回答
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()
    }
}

显然,你可以添加自己的错误处理和你有什么,但希望这说明了在一个属性中保存闭包并在你的委托回调时调用它的想法。

© www.soinside.com 2019 - 2024. All rights reserved.