从块

时间:2015-12-09 10:37:03

标签: objective-c-blocks

-(void) ReverseGeocode
{

    CLGeocoder *geocoder=[[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:self.toLocation
                   completionHandler:^(NSArray *placemarks, NSError *error){
                       if(error){
                           NSLog(@"Geocode failed with error: %@",error);
                           return;
                       }
                       if(placemarks &&placemarks.count>0){
                           CLPlacemark *placemark=placemarks[0];
                           NSDictionary *addressDictionary=placemark.addressDictionary;
                           NSString *Address=[addressDictionary objectForKey:(NSString*)
                                              kABPersonAddressStreetKey];
                          NSString *City=[addressDictionary objectForKey:(NSString*)
                                           kABPersonAddressCityKey];
                          NSString *State=[addressDictionary objectForKey:(NSString*)
                                            kABPersonAddressStateKey];
                          NSString *Zip=[addressDictionary objectForKey:(NSString*)
                                          kABPersonAddressZIPKey];
                       NSString *adress=[NSString localizedStringWithFormat:@"%@ %@ %@ %@ %@",
                                                 Address,City,State,@"United States",Zip];
                     //  return adress;
                       }

                   }];

}

以上是反向地理编码的方法。 我正在尝试检索最终结果NSString adress。我怎样才能做到这一点。我有很多这样的方法需要检索数据。

1 个答案:

答案 0 :(得分:1)

- (void)reverseGeocodeWithCompletionHandler:(void (^)(NSString *address))completionHandler {

    [geocoder reverseGeocodeLocation:self.toLocation
               completionHandler:^(NSArray *placemarks, NSError *error){
                   if(error) {
                       NSLog(@"Geocode failed with error: %@",error);
                       completionHandler(nil);
                   } else if {
                       if(placemarks &&placemarks.count>0) {
                           //...
                           NSString *adress=[NSString localizedStringWithFormat:@"%@ %@ %@ %@ %@",
                                             Address,City,State,@"United States",Zip];
                           completionHandler(address);
                   }

               }];
}

像这样调用这个方法:

[obj reverseGeocodeWithCompletionHandler:^(NSString *address) {
    NSLog(@"Address is = %@", address);
}];