这是我正在使用的代码片段。我有一个模型叫x_locator
. 当我对模型进行多线程处理时,maps.google.com 返回 620 错误(请求太多太快),但是当我将模型留在主线程上时,它工作正常......只有在发出请求时 UI 被锁定.
-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr {
NSString *urlStr = [NSString stringWithFormat:@"http://maps.google.com/maps/geo? q=%@&output=csv",
[addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *locationStr = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlStr]];
NSArray *items = [locationStr componentsSeparatedByString:@","];
double lat = 0.0;
double lon = 0.0;
if([items count] >= 4 && [[items objectAtIndex:0] isEqualToString:@"200"]) {
lat = [[items objectAtIndex:2] doubleValue];
lon = [[items objectAtIndex:3] doubleValue];
}
else {
NSLog(@"Address, %@ not found: Error %@",addressStr, [items objectAtIndex:0]);
}
CLLocationCoordinate2D location;
location.latitude = lat;
location.longitude = lon;
return location;
}
编辑:这是我尝试使用 GCD 的方式......这是在我的 ViewController 中
- (void)viewDidLoad
{
[super viewDidLoad];
//set any delegates
self.locationManager.delegate = self;
[locationManager startUpdatingLocation];
fuelMapView.showsUserLocation = YES;
[self setInitialRegion];
locationManager.distanceFilter = 100;
//create the model
x_locator = [[Locator alloc]init];
x_locator.delegate = self;
dispatch_queue_t finder = dispatch_queue_create("Locator", NULL);
//if I do this, only some of the locations are found. If I leave it on the main thread, all locations are found.
dispatch_async(finder, ^{
[x_locator getUsersZipUsingLocation:[locationManager location]];
});
}
所做getUsersZipUsingLocation:
的只是使用反向地理编码获取用户的邮政编码,然后它调用另一个方法来检索地址数组(根据用户的邮政编码),最后每个地址都使用转换为坐标位置-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr
编辑2:我很犹豫是否要完整发布代码,因为人们可能会失去对问题的关注并继续判断我的编码是否优雅......
无论如何...在调用该方法之前-(CLLocationCoordinate2D) getLocationFromAddressString:(NSString*) addressStr
,我必须将地址组合成可以作为变量传递的形式addressStr
。地址是分块到达的,所以我组装这些部分,然后继续从 url 获取数据......
NSString *urlStr = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
[addressStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
数据返回后,我说[NSThread sleepForTimeInterval:0.05];
并接受下一个请求。
感谢您的评论和时间:)