当我需要解析Feed
JSON时,我总是使用这个解决方案.
https://stackoverflow.com/a/20077594/2829111
但是现在不推荐使用sendAsynchronousRequest,我仍然坚持使用这段代码
__block NSDictionary *json; [[session dataTaskWithURL:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) { // handle response json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"Async JSON: %@",json); [collectionView reloadData]; }] resume];
有了这个,reloadData参数需要很长时间才能执行.我已经尝试用以下方法强制回到主队列:
__block NSDictionary *json; [[session dataTaskWithURL:request completionHandler:^(NSData *data,NSError *error) { // handle response json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; NSLog(@"Async JSON: %@",json); dispatch_sync(dispatch_queue_create("com.foo.samplequeue",NULL),^{[collectionView reloadData}); }] resume];
解决方法
问题是完成处理程序不在主队列上运行.但是所有UI更新必须在主队列上进行.所以将它发送到主队列:
[[session dataTaskWithURL:request completionHandler:^(NSData *data,NSError *error) { // handle response NSError *parseError; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; // do something with `json` dispatch_async(dispatch_get_main_queue()),^{[collectionView reloadData]}); }] resume];