Search code examples
xcodelockingdispatch

How can I wait for result from geocodeAddressString iPhone


I know its something to do with locks or dispatch groups, but I just cant seem to code it...

I need to know if the address was a valid address before leaving the method. Currently the thread just overruns and returns TRUE. I've tried locks, dispatchers the works but can't seem to get it correct. Any help appreciated:

- (BOOL) checkAddressIsReal
{
    __block BOOL result = TRUE;

    // Lets Build the address
    NSString *location = [NSString stringWithFormat:@" %@ %@, %@, %@, %@", streetNumberText.text, streetNameText.text, townNameText.text, cityNameText.text, countryNameText.text];

    // Put a pin on it if it is valid

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder geocodeAddressString:location
                 completionHandler:^(NSArray* placemarks, NSError* error) {
        result = [placemarks count] != 0;
    }];

    return result;
}

Solution

  • The documentation says that CLGeocoder calls the completionHandler on the main thread. Since you are probably also calling your method from the main thread it cannot wait for the geocoder's answer without giving it the opportunity to deliver the result.

    That would be done by polling the runloop, using some API as -[NSRunLoop runMode:beforeDate:].

    The disadvantage is that depending on the mode this will also deliver events and fire timers while waiting for the result.