我正在尝试将一个位置(CLLocation)解析为一个字符串。
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,因为completionHandler在后台运行。当completionHandler完成时,我很难理解如何更新字符串?
谢谢。
发布于 2015-01-02 23:51:19
如果要在textField中使用字符串(如注释中所示),请执行以下操作:
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的形式传递一个闭包:
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
}
}您可能希望以不同的方式处理错误等。这应该足够让你开始工作了。
https://stackoverflow.com/questions/27749854
复制相似问题