试图获取城市的名称,同时具有纬度和经度。
在模型类 Location
中,我正在使用 CLGeocoder(CoreLocation 的一部分)附带的 reverseGeocodeLocation(location: , completionHandler: )
函数。
func getLocationName() {
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String {
self.currentCity = city
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
})
}
但是,在 ViewController
中,在运行 getLocationName()
之后,location.currentCity
为 nil
,因为完成处理程序是异步的,而且还没有完成。
如何确保完成处理程序已完成运行,以便我可以访问 location.currentCity
?
最佳答案
在你的 getLocationName 中传递一个闭包作为函数参数 您可以在 reverseGeocodeLocation 闭包内部调用。
func updateLocation(currentCity : String) -> Void
{
print(currentCity)
}
func getLocationName(callback : @escaping (String) -> Void)
{
let geoCoder = CLGeocoder()
let location = CLLocation(latitude: currentLatitude, longitude: currentLongitude)
geoCoder.reverseGeocodeLocation(location, completionHandler: { placemarks, error in
guard let addressDict = placemarks?[0].addressDictionary else {
return
}
if let city = addressDict["City"] as? String
{
self.currentCity = city
callback(city)
print(city)
}
if let zip = addressDict["ZIP"] as? String {
print(zip)
}
if let country = addressDict["Country"] as? String {
print(country)
}
})
}
在您的 ViewController 中...
getLocationName(callback: updateLocation)
关于swift - 从异步完成处理程序获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236831/