查看此代码:
func getReversedGeocodeLocation(location: CLLocation, completionHandler: @escaping ()->()) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
if let addressDictionary: [AnyHashable: Any] = pm.addressDictionary,
let addressDictionaryFormatted = addressDictionary["FormattedAddressLines"] {
let address = (addressDictionaryFormatted as AnyObject).componentsJoined(by: ", ")
self.addressInViewController = address
}
completionHandler()
}
} else {
print("Problem with the data received from geocoder")
}
})
}
在视图控制器中
override func viewDidLoad() {
var addressInViewController = String()
getReversedGeocodeLocation(location: location, completionHandler: {
print("After geo finished")
})
}
这是一个使用闭包的简单例子。如您所见,当反向geo完成时,它将更新在函数本身外部定义的addressInViewController变量。当谈到闭包时,我有点困惑,但我知道它实际上是将另一个函数作为参数传入一个函数。因此,我可以传入类似(String:x)->()的内容,而不是从主reverse geo函数填充地址变量并将其传递给它的位置()->()?我试过这么做,但它说“x”是未定义的。如果这是可以实现的,那么我想我可以使用闭包以更好的方式分离我的代码。
谢谢,祝你有个愉快的一天:)
最佳答案
像这样定义你的方法
func getReversedGeocodeLocation(location: CLLocation, completionHandler: @escaping (_ value : Any)->()) {
CLGeocoder().reverseGeocodeLocation(location, completionHandler: {(placemarks, error) -> Void in
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks != nil {
if placemarks!.count > 0 {
let pm = placemarks![0]
if let addressDictionary: [AnyHashable: Any] = pm.addressDictionary,
let addressDictionaryFormatted = addressDictionary["FormattedAddressLines"] {
let address = (addressDictionaryFormatted as AnyObject).componentsJoined(by: ", ")
self.addressInViewController = address
}
completionHandler(address)
}
} else {
print("Problem with the data received from geocoder")
}
})
}
override func viewDidLoad() {
var addressInViewController = String()
getReversedGeocodeLocation(location: location, completionHandler: { (_ values : Any) in
self. addressInViewController = values
})
}
根据需要将数据类型设置为
Value
。