NSURLSessionDataTask表现得非常慢

Nil*_*ne- 3 parsing json objective-c nsurlsession

我从网上获取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];
Run Code Online (Sandbox Code Playgroud)

[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]
Run Code Online (Sandbox Code Playgroud)

NSURLSession比第一种方法慢10到30秒.我不明白为什么会这样.在这种情况下,搜索字符串返回27个不同的位置,如果这很重要的话

干杯.

Cou*_*per 11

您需要确保在主线程上执行UIKit方法.

完成处理程序的块将在"委托队列"上执行(参见delegateQueue属性NSURLSession).

您可以通过两种方式完成此任务:设置作为主队列([NSOperationQueue mainQueue])或使用的委托队列

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self loadAnnotationsAndCenter:YES]; 
});
Run Code Online (Sandbox Code Playgroud)

在你的完成块.