Question

I am trying to return the user's state using reverseGeocodeLocation. I am using this code to pull the user's location from another view.

NSString *userState =[(PDCAppDelegate *)[UIApplication sharedApplication].delegate     
getAddressFromLocation]; 

I am getting the following error: 'NSInvalidArgumentException', reason: '-[PDCAppDelegate getAddressFromLocation]: unrecognized selector sent to instance. The code I am using in PDCAppDelegate to return the address is below.

-(NSString *)getAddressFromLocation:(CLLocation *)location {
NSString *address;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError 
*error)
 {
     if(placemarks && placemarks.count > 0)
     {
         CLPlacemark *placemark= [placemarks objectAtIndex:0];

         NSString *address = [NSString stringWithFormat:@"%@ %@,%@ %@", [placemark 
subThoroughfare],[placemark thoroughfare],[placemark locality], [placemark 
administrativeArea]];

         NSLog(@"%@",address);
     }

 }];

return address;
}

Anyone know how to fix this? Thank you!

Was it helpful?

Solution

The CLGeocoder method reverseGeocodeLocation:completionHandler: runs asynchronously. That means you can't return the address from getAddressFromLocation: because the address is simply not set when you return from this method.

When the geocoder received the address (or the call caused an error) it will run the completionHandler. You have to set, or show the address from within the completion handler.

Easiest would be to send a NSNotification, probably not the best way though:

-(void)getAddressFromLocation:(CLLocation *)location {
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
     {
         if (!placemarks) {
             // handle error
         }

         if(placemarks && placemarks.count > 0)
         {
             CLPlacemark *placemark= [placemarks objectAtIndex:0];
             NSString *address = [NSString stringWithFormat:@"%@ %@,%@ %@", [placemark subThoroughfare],[placemark thoroughfare],[placemark locality], [placemark administrativeArea]];

             // you have the address.
             // do something with it.
             [[NSNotificationCenter defaultCenter] postNotificationName:@"MBDidReceiveAddressNotification" 
                  object:self 
                userInfo:@{ @"address" : address }];
         }
     }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top