[英]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.