如何同步调用CLGeocoder方法

How to call CLGeocoder method synchronously

我有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)

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

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 代码中进行地理编码,但我想知道如何将其保存在单独的 class.

你需要完成

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 {,因为地理编码器在后台线程中异步运行