【问题标题】:ios - AFNetworking blocking main thread during downloadios - AFNetworking 在下载期间阻塞主线程
【发布时间】: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


【解决方案1】:

您正在更新进度块中的进度视图。因为 AFNetworking 本质上是异步的,所以这些请求中的每一个都将同时堆叠和运行。如果您运行其中的 200 个,那将会冻结应用程序。尝试使用NSOperationQueuemaxConcurrentOperationCount 来限制并发线程数。

或者,您可以省去所有麻烦,只需使用

【讨论】:

  • 非常感谢您的帮助。当我读到这个问题时:stackoverflow.com/questions/13133591/… 我似乎明白 AFNetworking 本身应该是异步的,对吧?
  • Hrm 好点。您正在更新进度块中的进度 UI - 其中有多少是同时运行的?
  • 我重新分析了我的代码,这是我的结论:下载是异步进行的,但问题是一旦下载完成,它就会调用成功块(位于主线程),依此类推,依此类推(他们一个接一个地完成)。所以主线程仍然被阻塞,这就是为什么没有更新进度......我该怎么办? (大约有 150 张图片/块)
  • 我看过了,但是你觉得我的新评论怎么样?我认为这是这里的主要问题!
  • 您也可以考虑使用 SDWebImage 之类的东西,它会自动完成所有这些操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-01
  • 2018-02-16
  • 1970-01-01
  • 2015-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多