如何同步调用CLGeocoder方法

时间:2019-03-02 22:12:50

标签: swift clgeocoder

我在ViewController代码中有

var location = CLLocation()
    DispatchQueue.global().sync {
        let objLocationManager = clsLocationManager()
        location = objLocationManager.findLocationByAddress(address: self.txtTo.stringValue)
    }
    lblToLatitude.stringValue = String(location.coordinate.latitude)
    lblToLongitude.stringValue = String(location.coordinate.longitude)

调用findLocationByAddress方法,该方法在像这样的单独类clsLocationManager中实现

func findLocationByAddress(address: String) -> CLLocation {
    let geoCoder = CLGeocoder()
    var location = CLLocation()
    geoCoder.geocodeAddressString(address, completionHandler: {(places, error) in
        guard error == nil else { return }
        location = places![0].location!
    })
    return location
}

我尝试通过DispatchQueue.global()。sync确保在将坐标传递到lblToLatitude和lblToLongitude标签之前执行了地理编码,但是它不起作用。当然,我可以在ViewController代码中进行地理编码,但是我想知道如何将其保存在单独的类中。

1 个答案:

答案 0 :(得分:0)

您需要完成

func findLocationByAddress(address: String,completion:@escaping((CLLocation?) -> ())) {
    let geoCoder = CLGeocoder() 
    geoCoder.geocodeAddressString(address, completionHandler: {(places, error) in
        guard error == nil else { completion(nil) ; return }
        completion(places![0].location!)
    }) 
}

打电话

findLocationByAddress { (location) in 
  if let location = location { 
      lblToLatitude.stringValue = String(location.coordinate.latitude)
      lblToLongitude.stringValue = String(location.coordinate.longitude)
  } 
}

由于地理编码器在后台线程中异步运行,因此也不需要DispatchQueue.global().sync {