0
我的完成處理程序有問題。下面是完成處理的功能,位於實用程序文件:完成處理程序異步
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)
}
}
}
})
}
,我稱之爲一個視圖控制器
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!
如何解決此問題?
按預期工作。工作完成後立即調用完成處理程序。當這項工作完成後,定期的控制流程將繼續 - 在你的情況下,這意味着執行了print語句。 –