2

我需要在队列中下载多个文件。当我尝试下载单个文件时,它工作得很好,但是当我尝试下载多个文件时,它在第一次下载的同时开始下载,我需要将它们排在队列中,直到第一次下载完成,然后再进行第二次下载。我正在使用 AFNetworking 库扩展 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];
4

1 回答 1

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 的操作队列后立即开始,但后续请求将依次等待前一个操作结束。

于 2013-03-11T15:25:59.477 回答