【发布时间】:2017-02-14 21:46:22
【问题描述】:
尝试获取城市名称,同时具有纬度和经度。
在模型类 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 ?
【问题讨论】:
-
只需访问
location.currentCityin完成处理程序或向getLocationName()添加另一个完成处理程序以异步返回数据。 -
您不必“确保完成处理程序已完成运行”,您只需在
completionHandler中使用location.currentCity做任何您想做的事情 -
@vadian 我需要访问视图控制器中的“location.currentCity”(在 Location 类之外)以更新 UI。添加另一个完成处理程序会更好吗,所以我不在模型类中更新 UI?您能否提供一个示例代码应该如何实现新的完成处理程序?
-
@AndrewBrooke 但我想用 viewController 中的 location.currentCity 更新我的 UI,并且我在模型类“Location”中没有视图控制器的实例。我应该创建那个实例,这样我就可以在完成处理程序中的某个地方执行“vcInstance.updateUI(currentCity)”吗?
标签: swift asynchronous core-location