在我们的代码中,我们调用一个方法,该方法应该从CLGeocoder 返回当前设备位置的地址。但问题是CLGeocoder异步执行请求并在完成后调用completionHandler,因此存在“延迟”。
有没有办法执行reverseGeocodeLocation并在方法中返回结果?所以基本上被调用的方法需要“等待”直到CLGeocoder的请求完成。
答案 0 :(得分:0)
func findGMSAddress(completion : @escaping (_ address : LocationModel)->()) {
let geoCoder = CLGeocoder()
let loca = CLLocation(latitude: self.location.latitude, longitude: self.location.longitude)
geoCoder.reverseGeocodeLocation(loca) { (placemarks, error) -> Void in
if error != nil {
print("Error getting location: \(String(describing: error))")
} else {
let placeArray = placemarks as [CLPlacemark]!
var placeMark: CLPlacemark!
placeMark = placeArray?[0]
self.location.name = placeMark.name ?? ""
self.location.adminArea = placeMark.administrativeArea ?? ""
self.location.locality = placeMark.locality ?? ""
self.location.thoroughFare = placeMark.thoroughfare ?? ""
completion(self.location)
}
}
}
使用上面这样的方法:
// show loader
self.findGMSAddress(completion: { (address) in
DispatchQueue.main.async {
// hide loader
// use address here
}
})