我试图获得" locality"来自使用CLGeocoder.reverseGeocodeLocation
的坐标,但当执行到达completionHandler时,括号内的代码将完全跳过self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)!
冻结应用程序。
我哪里错了?
func updateLocation() {
let location = CLLocation.init(latitude: currentCoordinates.latitude, longitude: currentCoordinates.longitude)
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
if (error != nil) {
print("Error")
}else {
let pm = placemarks as [CLPlacemark]!
if pm.count > 0 {
self.place = pm.first
self.stopUpdatingLocation()
}
}
})
self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)!
}
答案 0 :(得分:0)
这称为异步编程。反向地理编码完成后,会在一段时间后调用完成处理程序。您需要在处理程序内调用UI更新。
您可以显示某种加载程序,它向用户指示正在进行操作。
func updateLocation() {
let location = CLLocation.init(latitude: currentCoordinates.latitude, longitude: currentCoordinates.longitude)
let geocoder = CLGeocoder()
//Show loader here
geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in
//hide loader here
if (error != nil) {
print("Error")
}else {
let pm = placemarks as [CLPlacemark]!
if pm.count > 0 {
self.place = pm.first
self.currentPlace = (self.place?.locality)! + ", " + (self.place?.thoroughfare)!
self.stopUpdatingLocation()
}
}
})
}