我的完成处理程序有问题。这是一个带有完成处理程序的函数,位于实用程序文件中:
func convertGeopointToCity(geopoint: PFGeoPoint, complete: (city: String, error: NSError?) -> Void) {
var city = ""
let latitude = geopoint.latitude
let longitude = geopoint.longitude
let location: CLLocation = CLLocation(latitude: latitude, longitude: longitude)
CLGeocoder().reverseGeocodeLocation(location, completionHandler: { placemarks, error in
if (error == nil) {
if let p = CLPlacemark?(placemarks![0]) {
if let city = p.locality {
city = " \(city)!"
print("Here's the city:\(city)")
complete(city: city, error: nil)
}
}
}
})
}
我在ViewController中调用
LocationUtility.instance.convertGeopointToCity(geopoint, complete: { result, error in
if error != nil {
print("error converting geopoint")
} else {
city = result as String
}
})
print("The city: \(city)")
输出清楚地表明该功能在运行块之前没有等待完成:
The city:
Here's the hood Toronto!
如何解决此问题?
答案 0 :(得分:0)
你应该把你的处理程序放在块中:
LocationUtility.instance.convertGeopointToCity(geopoint, complete: { result, error in
if error != nil {
print("error converting geopoint")
} else {
city = result as String
// do other stuff here, or call a method
print("The city: \(city)")
}
})
CLGeocoder().reverseGeocodeLocation
是异步的。一旦地理编码完成,就会调用完成块,更有可能在打印附加后调用。
您应该在完整块调用的另一个函数中执行操作,或者向块本身添加一些代码。