使用CLGeocoder重复地理编码后,kCLErrorDomain错误2
我的应用程序中有一个搜索栏,用户可以输入一个地址,它会提供地理编码结果。根据以下代码,结果将根据用户类型进行更新:
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.)"
在重新加载整个ViewController之前,地理编码器不会再次运行。为什么会发生这种情况,我该怎么做才能解决它?
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?
我相信原因如下:
Apple的地理编码器不会以同样的方式回答每个请求。相反,来自某个设备的第一个请求会得到快速回复,但如果设备发送了100个或更多请求,则答案会越来越慢或者请求根本没有得到应答,这可能会导致您的错误。
重新加载视图控制器时,这只需要时间,地理编码服务器更愿意再次回答。
基本上,你不能对它做任何事情,因为地理编码器服务器想要保护自己免受来自单个设备的请求的过载。您只需限制在那里发送的请求数量。
BTW: docs 说你不应该每分钟发送多个地理编码请求。
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".