如何等待执行LocationService回调?

时间:2019-10-16 10:17:13

标签: ios swift callback location performselector

我试图执行一次位置服务。从另一个对象类调用此LocationService,它将把位置信息添加到参数中。所有这些都是一个对象。

问题是,当我初始化对象时,所有内容都填充了较少的位置数据,位置数据将在几毫秒后填充。

我需要等到回调执行完毕后,才能成功生成完整的对象

因此考虑到我有下一个“ LocationService ”类

public class LocationService: NSObject, CLLocationManagerDelegate{
    let manager = CLLocationManager()
    var locationCallback: ((CLLocation?) -> Void)!
    var locationServicesEnabled = false
    var didFailWithError: Error?

    public func run(callback: @escaping (CLLocation?) -> Void) {
        locationCallback = callback
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
        manager.requestWhenInUseAuthorization()
        locationServicesEnabled = CLLocationManager.locationServicesEnabled()
        if locationServicesEnabled {
            manager.startUpdatingLocation()
        }else {
            locationCallback(nil)
        }
    }

   public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        locationCallback(locations.last!)
        manager.stopUpdatingLocation()
    }

    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        didFailWithError = error
        locationCallback(nil)
        manager.stopUpdatingLocation()
    }

    deinit {
        manager.stopUpdatingLocation()
    }
}

从这样的对象类中被称为

class ObjectX: NSObject{
    //Class variables
    @objc override init() {

    let getLocation = LocationService()
    getLocation.run {
        if let location = $0 {
            //get location parameters
    }}

最后,ObjectX类是在其他地方启动和使用的

let getLocation = ObjectX()
//After initiate it I use the object for other purposes, but here the object is not complete, the location parameters have not been populated yet

如何在正在调用它的类中等待回调执行?我应该使用getLocation.performSelector()吗?怎么样?

1 个答案:

答案 0 :(得分:0)

也许这不是解决此问题的最佳方法,但对我有用。

基本上,无需在过程中创建ObjectX并进行设置,而是将位置服务称为before,然后在回调中将对ObjectX进行初始化,然后可以使用以下方式设置ObjectX的位置参数:我们在对象中收到的位置对象。

我们从初始化程序中删除了位置设置

class ObjectX: NSObject{
    //Class variables
    @objc override init() {
      //Setting the rest of the parameters that are not location
}}

然后初始化类的类,我们初始化并运行LocationService,然后在回调中创建ObjectX并设置位置参数

 let ls = LocationService()
 ls.run { location in
     let objectX = ObjectX()
     objectX.location = location
   //We can use the object here
 }