I am trying to do reverse-geocoding with current location, retrieve City and State and save it to CoreData entity. In the below code, as soon as the save button is hit by user, I expect reverse geocoding to take place and save city and state information to Core Data. But when I try to execute below code, reverse geocoding part is not executed and no data is saved to Core Data. One pointer that I found in other threads is that reverse-geocoding takes place in an independent thread and later part of this function gets kicked in without reverse geocoding taking place. Can someone please guide me on how to proceed with this problem? I'm still new to iOS app development, so detailed reply would be highly appreciated. Thanks in advance!
- (IBAction)save:(id)sender {
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
//Update current location
[self.locationManager startUpdatingLocation];
// Reverse Geocoding
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:self.locationManager.location completionHandler:^(NSArray *placemarks, NSError *error)
{
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new device
NSManagedObject *newPlace = [NSEntityDescription insertNewObjectForEntityForName:@"Place" inManagedObjectContext:context];
[newPlace setValue:placemark.locality forKey:@"city"];
[newPlace setValue:placemark.administrativeArea forKey:@"state"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}
Try this:
As you can see I put the code to save the data inside the feedback-callback. The callback is asynchronous and is called after the information became available (which can take time; e.g. 2 seconds). If you try to save the data before you've received it, you will indeed store nothing.