多线程方法的completionHandler
block可能运行在非主线程上。两种处理方法:
- 在block里手动加上
dispatch_async(dispatch_get_main_queue(), ^{});
1 2 3 4 5 6 7 8 9 10 11 12
| NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:imgRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { dispatch_async(dispatch_get_main_queue(), ^{}); [self performSelectorOnMainThread:@selector(doUIthings) withObject:nil waitUntilDone:NO]; }];
[task resume];
|
- 带有
delegateQueue
等参数的方法,可传入主线程队列,然后blockcompletionHandler
便运行在主线程了。
1 2 3 4 5 6 7 8 9 10
| NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:imgRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[task resume];
|