我正在尝试使用当前位置进行反向地理编码,检索City和State并将其保存到CoreData实体。在下面的代码中,只要用户点击保存按钮,我希望反向地理编码发生,并将城市和州的信息保存到核心数据。但是当我尝试执行下面的代码时,反向地理编码部分不会执行,也不会将数据保存到Core Data。我在其他线程中发现的一个指针是反向地理编码发生在独立线程中,稍后部分此功能会被踢入,而不会发生反向地理编码。有人能指导我如何解决这个问题吗?我还是iOS应用程序开发的新手,非常感谢您的详细回复。提前致谢!如何在Objective-C中将反向地理编码数据保存到CoreData中?
- (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];
}
'reverseGeocodeLocation'是一个异步调用。如果您需要使用'placemark'做些事情,请将代码移到完成处理程序中。 – Sulthan
我尝试着在开发者的答案中做了以下建议,但是在我的评论中遇到了一个问题,如下所述。 – hellSigma