我正在从网络上获取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文件中检索纬度和经度,并将其用于在地图上显示标记。
我决定使用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个不同的位置。
谢谢。