我从web上获取JSON数据,解析它,然后使用它在地图上播放引脚。
下面是方法一,它没有问题:
NSString *CLIENT_ID = @"SECRET_ID";
NSString *CLIENT_SECRET = @"CLIENT_SECRET";
NSString *SEARCH = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?near=gjovik&query=cafe&client_id=%@&client_secret=%@&v=20140119", CLIENT_ID, CLIENT_SECRET];
NSURL *searchResults = [NSURL URLWithString:SEARCH];
NSData *jsonData = [NSData dataWithContentsOfURL:searchResults];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.venues = dataDictionary[@"response"][@"venues"];
[self loadAnnotationsAndCenter:YES];[self loadAnnotationsAndCenter:YES];从JSON文件中检索lat和lng,并使用它们在地图上显示引脚。
我决定使用NSURLSession更改我的代码。看上去是这样的:
NSString *CLIENT_ID = @"SECRET_ID";
NSString *CLIENT_SECRET = @"CLIENT_SECRET";
NSString *SEARCH = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?near=gjovik&query=cafe&client_id=%@&client_secret=%@&v=20140119", CLIENT_ID, CLIENT_SECRET];
NSURL *URL = [NSURL URLWithString:SEARCH];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.venues = dataDictionary[@"response"][@"venues"];
[self loadAnnotationsAndCenter:YES];
}];
[task resume]NSURLSession比第一种方法慢10到30秒。我不明白为什么是这样。在本例中,搜索字符串返回27个不同的位置(如果这重要的话)。
干杯。
发布于 2014-01-22 12:26:45
您需要确保在主线程.上执行UIKit方法。
完成处理程序的块将在“委托队列”上执行(请参阅NSURLSession的NSURLSession属性)。
您可以通过两种方式来完成这一任务:要么设置委托队列(即主队列([NSOperationQueue mainQueue]) ),要么使用
dispatch_async(dispatch_get_main_queue(), ^{
[self loadAnnotationsAndCenter:YES];
});在你的完井区。
发布于 2015-09-09 14:24:09
在Swift:
dispatch_async(dispatch_get_main_queue()) {
}https://stackoverflow.com/questions/21282229
复制相似问题