在模特的课堂上Location
,我得到当前城市的名称:
var currentLatitude: Double!
var currentLongitude: Double!
var currentLocation: String!
var currentCity: String!
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)
}
self.nowUpdateUI()
})
}
在视图控制器中,我想更新 UI 并更新标签以显示当前城市。
然而,self.currentCity = city
发生在闭包内部。因此,如果我只是在视图控制器中运行一个函数:
func updateUI() {
cityLbl.text = Location.sharedInstance.currentCity
}
- 我什么也没得到,因为关闭还没有完成运行。
建议我添加一个完成处理程序
getLocationName()
在其中,执行对将更新 UI 的函数的调用。
然而,从所有关于闭包、完成处理程序的教程中,我不清楚如何实现这一点。
如何构造完成处理程序,将其作为参数传递给getLocationName()
以及如何打电话getLocationName
从视图控制器?
要处理这种情况,您有多种选择。
-
Create delegate/protocol
与您的位置类别
- 创建一个协议并使用您的实现该协议方法
ViewController
并在你的中声明它的实例Location
班级。之后在completionHandler
of reverseGeocodeLocation
调用这个委托方法。检查 Apple 文档Protocol更多细节。
-
您可以创建completionHandler
和你的getLocationName
的方法Location
class.
-
Add completionHandler
with getLocationName
并称之为completionHandler
在 - 的里面completionHandler
of reverseGeocodeLocation
像这样。
func getLocationName(completionHandler: @escaping (_ success: Bool) -> 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 {
completionHandler(false)
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)
}
completionHandler(true)
//self.nowUpdateUI()
})
}
Now in ViewController
你在哪里调用这个函数调用你的updateUI
完成块内的方法。
Location.sharedInstance.getLocationName { (success) in
if success {//If successfully got response
self.updateUI()
}
}
-
您可以添加观察者(NS)NotificationCenter
.
- 注册观察者
(NS)NotificationCenter
然后将通知发布在completionHandler
of reverseGeocodeLocation
。您可以通过此获得更多详细信息StackOverflow 帖子.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)