2013-03-11 40 views
2

我需要在队列中下载多个文件。当我尝试下载单个文件时,它的工作原理完全正常,但是当我尝试下载多个文件时,它会在首次下载的同时开始下载,直到第一次下载完成,然后再次下载为止。我正在使用AFNetworking库扩展AFDownloadRequestOperation。以下是我的代码。请帮助我,如果有任何事情我做错了。如何在iOS中的队列中下载多个文件

  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

最好是检查AFDownloadRequestOperation文档,了解如何执行此操作。如果这没有帮助,则从第一个请求的成功或失败完成块开始第二个请求。为什么要按顺序进行操作,有没有特定的原因? – fishinear 2013-03-11 13:33:24

+0

看看http://stackoverflow.com/questions/11186854/download-a-file-image-with-afnetworking-in-ios – 2013-03-11 14:13:29

+0

我不熟悉AF *类,但如果它是真实的[NSOperation]的子类可以很简单地与[NSOperationQueue]集成。或者也许AF *类已经做到了。 – EricLeaf 2013-03-11 14:55:27

回答

2

创建请求,并将它们添加到AFHTTPClient的操作队列的一个实例:因为它被添加到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]; 
} 

你的第一个请求将尽快启动,但随后的请求将依次等待以前的操作结束。

+0

感谢它帮助了我很多。 – user748001 2013-03-12 13:22:26

+0

@Matt感谢您的结构..有时因为我在for循环中创建AfhttpClient对象,并且因为每个操作都有它自己的客户端对象,所以我得到失败错误..也感谢您解决我的问题问题 – 2013-08-21 10:32:24