多线程方法的completionHandlerblock可能运行在非主线程上。两种处理方法:

  1. 在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];//no delegateQueue
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(), ^{/* do UI things */});
//or
[self performSelectorOnMainThread:@selector(doUIthings) withObject:nil waitUntilDone:NO];
}];

[task resume];
  1. 带有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]];//get the 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) {
/* do UI things */
}];

[task resume];

 评论

 无法加载Disqus评论系统,请确保您的网络能够正常访问。

©2019 派大星星星星

本站使用 Material X 作为主题 , 总访问量为 次 。