我使用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];
}文本。这部分如果真的很快的话。但是我以为AFNetworking不应该在我下载的时候阻塞主线程?这也不允许我跟踪download...Am的进度,我做错了什么或曲解了什么?
发布于 2015-09-13 01:12:39
您正在更新进度块中的进度视图。因为AFNetworking本质上是异步的,所以这些请求中的每一个都将堆叠并同时运行。如果你正在运行200个这样的应用程序,这会冻结应用程序。尝试使用NSOperationQueue的maxConcurrentOperationCount来限制并发线程的数量。
或者,你也可以省去所有的麻烦,直接使用sdwebimage。
https://stackoverflow.com/questions/32541113
复制相似问题