kCLErrorDomain error 2 after geocoding repeatedly

2020-02-05 11:32发布

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?

3条回答
甜甜的少女心
2楼-- · 2020-02-05 12:13

I had this problem while picking location for messenger application. My solution was to introduce delay of 3 seconds, after user stop panning map, before geocoder call. To ensure that user want exactly that location.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-05 12:23

Note that this same error is returned when the device is offline.

查看更多
聊天终结者
4楼-- · 2020-02-05 12:31

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".

查看更多
登录 后发表回答