问题描述
我正在尝试将位置(CLLocation)解析为字符串.
I'm trying to parse a location (CLLocation) into a String.
func locationToString (currentLocation: CLLocation) -> String? {
var whatToReturn: String?
CLGeocoder().reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks: [AnyObject]!, error: NSError!) in
if error == nil && placemarks.count > 0 {
let location = placemarks[0] as CLPlacemark
whatToReturn = "\(location.locality) \(location.thoroughfare) \(location.subThoroughfare)"
}
})
return whatToReturn
}
很显然,由于完成处理程序在后台运行,因此whatToReturn始终返回null.我很难理解completedHandler完成后如何更新我的字符串?
Obviously, whatToReturn always returns null, because completionHandler runs in the background.I'm having a hard time understanding how do I update my String when completionHandler finishes?
谢谢.
推荐答案
如果要在textField中使用字符串,如注释中所示,请执行以下操作:
If you want to use your string in a textField, like indicated in your comments, do this:
func getAndDisplayLocationStringForLocation(currentLocation: CLLocation) {
CLGeocoder().reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks: [AnyObject]!, error: NSError!) in
if error == nil && placemarks.count > 0 {
let location = placemarks[0] as CLPlacemark
self.textField.text = "\(location.locality) \(location.thoroughfare) \(location.subThoroughfare)"
}
})
}
但是,如果您需要在其他地方访问,则可以将闭包作为arg传递:
However, if you need access elsewhere, perhaps pass a closure as an arg:
func getAndDisplayLocationStringForLocation(currentLocation: CLLocation, withCompletion completion: (string: String?, error?, error: NSError?) -> ()) {
CLGeocoder().reverseGeocodeLocation(currentLocation, completionHandler: { (placemarks: [AnyObject]!, error: NSError!) in
if error == nil && placemarks.count > 0 {
let location = placemarks[0] as CLPlacemark
completion(string: "\(location.locality) \(location.thoroughfare) \(location.subThoroughfare)", error: nil)
} else {
completion(nil, error)
}
})
}
然后像这样呼叫:
yourModel.getAndDisplayLocationStringForLocation(someLocation) { (string: String?, error: NSError?) -> () in
if (error == nil) {
self.textField.text = string
}
}
您可能希望以不同方式处理错误等.这应该足以让您入门.
You may want to handle error etc. differently. This should be enough to get you started.
这篇关于iOS Swift-CLGeocodercompleteHandler块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!