kCLErrorDomain error 2 after geocoding repeatedly with CLGeocoder

jburns20 picture jburns20 · Jul 25, 2013 · Viewed 17.5k times · Source

I have a search bar in my application that the user can type an address into, and it will come up with the geocoded result. The result updates as the user types, according to the following code:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    ...
    if (self.geocoder.geocoding) [self.geocoder cancelGeocode];
    [self.geocoder geocodeAddressString:searchText completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error != nil) {
            NSLog(@"ERROR during geocode: %@", error.description);
            return;
        }
        //update the view
    }];
}

This works for the first few characters the user enters into the search field. However, after the user types more characters repeatedly, the geocoder starts giving the following error (which I know means that there was a problem with the network):

ERROR during geocode: Error Domain=kCLErrorDomain Code=2 "The operation couldn’t be completed. (kCLErrorDomain error 2.)"

The geocoder does not work again until the entire ViewController is reloaded. Why could this be happening, and what can I do to resolve it?

Answer

Reinhard Männer picture Reinhard Männer · Jul 25, 2013

I believe the reason is the following:
Apple's geocoder does not answer every request in the same way. Instead, the first requests from a certain device are answered quickly, but if the device has sent say 100 requests or more, the answers arrive slower and slower or requests are not answered at all, which might cause your error.
When you reload the view controller, this simply takes time, and the geocoding server is more willing to answer again. Essentially, you cannot do anything about it, since the geocoder sever wants to protect itself from being overloaded by requests from a single device. You simply had to limit the number of requests that you send there.
BTW: The docs say "you should not send more than one geocoding request per minute".