[英]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)
调用在单独的类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代码中进行地理编码,但是我想知道如何将其保留在单独的类中。
你需要完成
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 {
因为地址解析器在后台线程中异步运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.