繁体   English   中英

iOS-AFNetworking在下载过程中阻止主线程

[英]ios - AFNetworking blocking main thread during download

我正在使用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日志都显示“ Finished” ...文本。 所以那部分如果真的很快。 但是我以为AFNetworking在下载时不应该阻止主线程吗? 这也不允许我跟踪下载进度...我做错了什么还是曲解了?

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

另外,您可以省去所有麻烦,而只需使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM