我需要在队列中下载多个文件。当我尝试下载单个文件时,它工作得非常好,但是当我尝试下载多个文件时,它会在第一次下载的同时开始下载,我需要将它们保留在队列中,直到第一次下载完成然后再次下载。我正在使用AFNetworking Library扩展AFDownloadRequestOperation。以下是我的代码。如果我有任何错误,请帮助我。
NSURLRequest *request = [NSURLRequest requestWithURL:videoURL];
AFDownloadRequestOperation *operation = [[AFDownloadRequestOperation alloc] initWithRequest:request targetPath:path shouldResume:YES];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if(operation.response.statusCode == 200) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Successfully Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if(operation.response.statusCode!= 200) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Error While Downloaded" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}];
[operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
float percentDone = ((float)totalBytesRead) / totalBytesExpectedToReadForFile;
delegate.progressDone = percentDone;
[progressTableView reloadData];
}];
[operation start];
答案 0 :(得分:2)
创建请求并将其添加到AFHTTPClient操作队列的实例中:
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:nil];
// Important if only downloading one file at a time
[client.operationQueue setMaxConcurrentOperationCount: 1];
NSArray *videoURLs; // An array of strings you want to download
for (NSString * videoURL in videoURLs) {
// …setup your requests as before
[client enqueueHTTPRequestOperation:downloadRequest];
}
您的第一个请求会在添加到AFHTTPClient的操作队列后立即开始,但后续请求将依次等待上一个操作结束。