【发布时间】:2015-09-12 16:29:43
【问题描述】:
我正在使用 AFNetworking 下载或多或少 200 张图像。问题是主线程在下载期间被阻塞,而不是在成功/失败阻塞期间。 这是我的代码:
imageDownloads=[[NSMutableArray alloc]init];
for(NSString *url in liens){
NSString *totalURL = [NSString stringWithFormat:@"http://%@", url];
[imageDownloads addObject:[[ImageDownload alloc] initWithURL:[NSURL URLWithString:totalURL] filename:nil]];
}
for (int i=0; i < imageDownloads.count; i++)
{
ImageDownload *imageDownload = imageDownloads[i];
[self downloadImageFromURL:imageDownload];
}
- (void)downloadImageFromURL:(ImageDownload *)imageDownload
{
NSURLRequest *request = [NSURLRequest requestWithURL:imageDownload.url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
imageDownload.totalBytesRead = totalBytesRead;
imageDownload.totalBytesExpected = totalBytesExpectedToRead;
[self updateProgressView];
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSAssert([responseObject isKindOfClass:[NSData class]], @"expected NSData");
imageDownload.totalBytesExpected = imageDownload.totalBytesRead;
[self updateProgressView];
//all kind of basic stuff here I left out: I get store the data inside CoreData
NSLog(@"finished %@", imageDownload);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error %@", error);
}];
[operation start];
}
基本上,当我启动代码时,线程被阻塞了大约 30-40 秒(图片总共大约 100MB),然后突然我可以看到所有 NSLog 日志都出现了“完成”...文本。所以那部分如果真的很快。但我认为 AFNetworking 不应该在我下载时阻止主线程?这也不允许我跟踪下载进度...我做错了什么或误解了什么?
【问题讨论】:
-
你试过使用 dispatch_async 吗?然后在完成块中就可以返回主线程了。
-
我不太明白什么时候必须在这里使用 dispatch_async?
-
在异步块中构建整个请求 - 只需确保当您的完成块调用任何 UI 更新时,它们会在主线程上调用。见stackoverflow.com/a/16283719/1214800
-
看看这个:stackoverflow.com/questions/13133591/… async 应该包含在 AFNetworking 中...
-
添加了一个答案以使其更清晰
标签: ios multithreading download afnetworking-2