我有视图控制器,提示用户输入一些位置信息,然后单击提交。发生这种情况时,数据会被投入到地点字典中,然后通过方法updatePlaceDictionary
和geocode
进行地理编码。然后[userListing saveInBackground]
将对象发送到在线数据库。以下是submit
方法,当用户填写信息并点击提交时调用该方法,以及updatePlaceDictionary
和geocode
方法:
- (void)submit{
PFObject* userListing = [PFObject objectWithClassName:@"userListing"];
[self updatePlaceDictionary];
[self geocode];
[userListing setObject:listingLocation forKey:@"location"];
[userListing saveInBackground];
[listings addObject:userListing];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)updatePlaceDictionary {
[self.placeDictionary setValue:self.streetField.text forKey:@"Street"];
[self.placeDictionary setValue:self.cityField.text forKey:@"City"];
[self.placeDictionary setValue:self.stateField.text forKey:@"State"];
[self.placeDictionary setValue:self.zipField.text forKey:@"ZIP"];
}
- (void)geocode{
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
listingLocation = [PFGeoPoint geoPointWithLatitude:coordinate.latitude longitude:coordinate.longitude];
} else {
NSLog(@"error");
}
}];
}
这三种方法都很完美。问题是,在submit
方法中,行:
[userListing setObject:listingLocation forKey@"location"];
最终只给键“location”一个值(0,0)。发生这种情况是因为地理编码异步运行,并且在到达上面一行时没有完成。如何在地理编码完成运行后设置此值?
答案 0 :(得分:0)
这里的整个代码必须有点异步。您的地理编码方法可以传入块回调,并在完成地理编码后调用它。
- (void)submit{
PFObject* userListing = [PFObject objectWithClassName:@"userListing"];
[self updatePlaceDictionary];
[self geocode:^{
[userListing setObject:listingLocation forKey:@"location"];
[userListing saveInBackground];
[listings addObject:userListing];
[self.navigationController popViewControllerAnimated:YES];
}];
}
- (void)updatePlaceDictionary {
[self.placeDictionary setValue:self.streetField.text forKey:@"Street"];
[self.placeDictionary setValue:self.cityField.text forKey:@"City"];
[self.placeDictionary setValue:self.stateField.text forKey:@"State"];
[self.placeDictionary setValue:self.zipField.text forKey:@"ZIP"];
}
- (void)geocode:(void (^)(void))callback {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressDictionary:self.placeDictionary completionHandler:^(NSArray *placemarks, NSError *error) {
if([placemarks count]) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
CLLocation *location = placemark.location;
CLLocationCoordinate2D coordinate = location.coordinate;
listingLocation = [PFGeoPoint geoPointWithLatitude:coordinate.latitude longitude:coordinate.longitude];
if (callback) {
callback();
}
} else {
NSLog(@"error");
}
}];
}