【问题标题】:NSURLSessionDataTask acting suspiciously slowNSURLSessionDataTask 动作缓慢
【发布时间】:2014-01-22 11:54:55
【问题描述】:

我从网络获取 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 个不同的位置,如果这很重要的话

干杯。

【问题讨论】:

    标签: objective-c json parsing nsurlsession


    【解决方案1】:

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

    完成处理程序的块将在“委托队列”上执行(参见NSURLSessiondelegateQueue 属性)。

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

    dispatch_async(dispatch_get_main_queue(), ^{ 
        [self loadAnnotationsAndCenter:YES]; 
    });
    

    在你的完成块中。

    【讨论】:

    【解决方案2】:

    在斯威夫特中:

    dispatch_async(dispatch_get_main_queue()) {
    }
    

    【讨论】:

    • 对代码的一些解释可能有助于理解问题以及为什么您的代码会解决问题
    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 2010-12-27
    • 2017-02-25
    • 2013-10-01
    • 2018-11-21
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多