Reputation: 3423
What is the best way to achieve this? I have a func that gets the reverseGeocode for a given longitude/latitude and it works just fine. But because it is asynchronous by the time it has got the address information I have already executed the lines to commit the address to a database. Do I need to completionHandle the completionHandler or is there some other way. I did try a do/while loop (don't laugh) and that didn't work.
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)
})
}
Upvotes: 0
Views: 154
Reputation: 131398
You simply need to move the code that commits your placemark information to the database inside your completion handler. If that code is called outside your reverseGeocode method, you can refactor reverseGeocode
to take a block as a parameter. Then invoke that block inside your completion block (presumably inside your if placemarks.count > 0
if block.)
Upvotes: 1