Ios 使用AFDownloadRequestOperation下载队列中的多个文件

Ios 使用AFDownloadRequestOperation下载队列中的多个文件,ios,download,background-image,afnetworking,Ios,Download,Background Image,Afnetworking,我使用AFDownloadRequestOperation+AFNetworking从服务器下载并恢复文件列表。该代码在一次下载和恢复多个文件方面非常有效。但是如何将操作队列中的所有操作排队并逐个执行操作呢 这是我目前的密码 // request the video file from server NSString *downloadURL = [NSString stringWithFormat:@"%@%@", [recipe download_url], [step valueForKe

我使用AFDownloadRequestOperation+AFNetworking从服务器下载并恢复文件列表。该代码在一次下载和恢复多个文件方面非常有效。但是如何将操作队列中的所有操作排队并逐个执行操作呢

这是我目前的密码

// request the video file from server
NSString *downloadURL = [NSString stringWithFormat:@"%@%@", [recipe download_url], [step valueForKey:@"video"]];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:downloadURL]];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:videoFile shouldResume:YES];

// done saving!
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"Done downloading %@", videoFile);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"Error: %ld", (long)[error code]);
}];

// set the progress
[operation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
     float progress = ((float)totalBytesReadForFile) / totalBytesExpectedToReadForFile;
     [progressBar setProgress:progress];
}];

[operation start];

您需要将这些操作添加到AFHTTPClient的operationQueue中,或者将它们添加到您自己创建的NSOperationQueue中

然后将您使用的队列的最大并发操作数设置为1

[operation start];

默认情况下,这将具有“由NSOperationQueue对象根据当前系统条件动态确定”的最大操作数

如果您真的想一次将所有内容强制为一个,请执行以下操作:

[YourAFHTTPClientSubclass sharedInstance].operationQueue.maxConcurrentOperationCount = 1;
这将阻止所有网络操作,直到操作完成

当然,您可以按照Audun的建议创建自己的操作队列,但最好让系统根据当前条件决定要做什么

根据您的使用情况,您可能希望将视频下载操作的优先级设置为低:

operation.queuePriority = NSOperationQueuePriorityLow
这将允许其他网络操作以比视频下载更高的优先级放置在队列中

operation.queuePriority = NSOperationQueuePriorityLow