我正在嘗試使用當前位置進行反向地理編碼,檢索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