【发布时间】:2015-06-29 03:42:34
【问题描述】:
我创建了一个类函数,其中包含一个闭包,可将位置坐标反向编码为地址字符串。我最初是在视图控制器中编写的,但我需要在几个地方运行这段代码。
我的问题是类函数在闭包运行之前返回字符串,所以返回的字符串是空白的。我有什么方法可以解决这个问题?有没有比使用类函数更好的方法来组织我的代码?
import CoreLocation
class LocationUtil: CLLocation {
class func getLocationAddress(location:CLLocation?) -> NSString {
var geocoder = CLGeocoder()
var addressString : String = ""
if location != nil {
geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in
var placemark:CLPlacemark!
if error == nil && placemarks.count > 0 {
placemark = placemarks[0] as CLPlacemark
if placemark.subThoroughfare != nil {
addressString = placemark.subThoroughfare + " "
}
if placemark.thoroughfare != nil {
addressString = addressString + placemark.thoroughfare + ", "
}
if placemark.locality != nil {
addressString = addressString + placemark.locality + ", "
}
if placemark.administrativeArea != nil {
addressString = addressString + placemark.administrativeArea + " "
}
if placemark.postalCode != nil {
addressString = addressString + placemark.postalCode + " "
}
if placemark.country != nil {
addressString = addressString + placemark.country
}
}
println("Address in closure: \(addressString)") //prints addresss
})
}
println("Address out of closure: \(addressString)") // doesn't print address
return addressString //this returns nothing
}
}
【问题讨论】:
标签: ios swift asynchronous closures