reverseGeocode - completionHandling 一个 completionHandler? (Swift)
reverseGeocode - completionHandling a completionHandler? (Swift)
实现此目标的最佳方法是什么?我有一个函数可以获取给定 longitude/latitude 的 reverseGeocode,它工作得很好。但是因为它在获得地址信息时是异步的,所以我已经执行了将地址提交到数据库的行。我需要 completionHandle completionHandler 还是有其他方法。我确实尝试了 do/while 循环(别笑),但没有用。
func reverseGeocode() -> Bool {
let geoCoder = CLGeocoder()
let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude)
geoCoder.reverseGeocodeLocation(newLocation, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) in
if error != nil {
println("LocationsMenu - Geocode failed with error: \(error.localizedDescription)")
}
if placemarks.count > 0 {
let myplacemark = placemarks[0] as! CLPlacemark
let addressDictionary = myplacemark.addressDictionary
let address = addressDictionary[kABPersonAddressStreetKey] as! NSString
let city = addressDictionary[kABPersonAddressCityKey] as! NSString
let state = addressDictionary[kABPersonAddressStateKey] as! NSString
let postcode = addressDictionary[kABPersonAddressZIPKey] as! NSString
let country = addressDictionary[kABPersonAddressCountryKey] as! NSString
println("\(address) \(city) \(state) \(postcode) \(country)")
}
self.showMap(placemarks[0] as! CLPlacemark)
})
}
您只需将提交地标信息的代码移动到完成处理程序内的数据库中。如果该代码是在您的 reverseGeocode 方法之外调用的,您可以重构 reverseGeocode
以将块作为参数。然后在您的完成块中调用该块(大概在您的 if placemarks.count > 0
if 块中。)
实现此目标的最佳方法是什么?我有一个函数可以获取给定 longitude/latitude 的 reverseGeocode,它工作得很好。但是因为它在获得地址信息时是异步的,所以我已经执行了将地址提交到数据库的行。我需要 completionHandle completionHandler 还是有其他方法。我确实尝试了 do/while 循环(别笑),但没有用。
func reverseGeocode() -> Bool {
let geoCoder = CLGeocoder()
let newLocation = CLLocation(latitude: valueLatitude, longitude: valueLongitude)
geoCoder.reverseGeocodeLocation(newLocation, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) in
if error != nil {
println("LocationsMenu - Geocode failed with error: \(error.localizedDescription)")
}
if placemarks.count > 0 {
let myplacemark = placemarks[0] as! CLPlacemark
let addressDictionary = myplacemark.addressDictionary
let address = addressDictionary[kABPersonAddressStreetKey] as! NSString
let city = addressDictionary[kABPersonAddressCityKey] as! NSString
let state = addressDictionary[kABPersonAddressStateKey] as! NSString
let postcode = addressDictionary[kABPersonAddressZIPKey] as! NSString
let country = addressDictionary[kABPersonAddressCountryKey] as! NSString
println("\(address) \(city) \(state) \(postcode) \(country)")
}
self.showMap(placemarks[0] as! CLPlacemark)
})
}
您只需将提交地标信息的代码移动到完成处理程序内的数据库中。如果该代码是在您的 reverseGeocode 方法之外调用的,您可以重构 reverseGeocode
以将块作为参数。然后在您的完成块中调用该块(大概在您的 if placemarks.count > 0
if 块中。)