使用iPhone中的AFNetworking下载队列中的文件

时间:2013-03-15 10:26:55

标签: iphone ios sdk afnetworking

我需要在队列中下载多个文件。现在我的代码工作,所有文件同时下载,但我需要一次下载一个文件,所有其他文件都在队列中,下面是代码,请让我知道我做错了什么。我只需要一次下载一个文件,所有其他文件都应该在队列中。

         AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:videoURL];
         [httpClient.operationQueue setMaxConcurrentOperationCount:1];
         for (NSURL *videoString in videoArray) {

             NSURLRequest *request = [NSURLRequest requestWithURL:videoString];

             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];
                 }
             }];

             [httpClient enqueueHTTPRequestOperation:operation];

             [operation setProgressiveDownloadProgressBlock:^(NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {

                 float percentDone = ((float)totalBytesRead) / totalBytesExpectedToReadForFile;

                 }
             }];

2 个答案:

答案 0 :(得分:1)

要一次将队列限制为一个操作,

您可以尝试在排队之前在每个操作之间添加依赖关系。

喜欢这个

[Operation2 addDependency:Operation1];

希望有所帮助!

答案 1 :(得分:0)

在阻止setCompletionBlockWithSuccess:

之后使用调度队列(GCD)

喜欢以下方式:

 dispatch_async(dispatch_get_main_queue(), ^{
// Call any method from on the instance that created the operation here.
  [self doSomework]; // example
 });