0

我努力实现使用AFNetworking的多个文件的下载机制。我想从多个url进入消息一个接一个地下载zip文件。我试着像下面的代码,但得到错误的 -如何从多个网址下载多个文件NSOperationQueue

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSOperationQueue addOperation:]: operation is already enqueued on a queue' 

这里是我的代码部分:

- (void) downloadCarContents:(NSArray *)urlArray forContent:(NSArray *)contentPaths { 

    NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init]; 

    for (int i=0; i< urlArray.count; i++) { 

     NSString *destinationPath = [self.documentDirectory getDownloadContentPath:contentPaths[i]]; 

     NSLog(@"Dest : %@", destinationPath); 

     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
     AFHTTPRequestOperation *operation = [manager GET:urlArray[i] 
               parameters:nil 
               success:^(AFHTTPRequestOperation *operation, id responseObject) { 

               } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

                NSLog(@"Error : %ld", (long)error.code); 
               }]; 

     operation.outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO]; 

     [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { 
      float percentage = (float) (totalBytesRead * 100)/totalBytesExpectedToRead; 
      [self.delegate downloadProgression:percentage]; 
     }]; 

     [operationQueue addOperation:operation]; 
    } 
} 

请帮助。

回答

3

当您拨打GET时,它已被添加到AFHTTPRequestionOperationManageroperationQueue。所以不要再将它添加到队列中。

此外,您应该在循环之前实例化一次AFHTTPRequestOperationManager,而不是在循环内重复。


还有其他问题与此代码,而不是试图解决所有这些问题,我建议你转换到AFHTTPSessionManager,它使用NSURLSession。旧的AFHTTPRequestOperationManager基于NSURLConnection,但现在不推荐使用NSURLConnection。事实上,AFNetworking 3.0已完全退役AFHTTPRequestOperationManager

因此,AFHTTPSessionManager再现可能看起来像:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 

for (NSInteger i = 0; i < urlArray.count; i++) { 
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlArray[i]]]; 
    NSURLSessionTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) { 
     [self.delegate downloadProgression:downloadProgress.fractionCompleted * 100.0]; 
    } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { 
     return [NSURL fileURLWithPath:[self.documentDirectory getDownloadContentPath:contentPaths[i]]]; 
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { 
     NSLog(@"File downloaded to: %@", filePath); 
     NSLog(@"Error: %@" error.localizedDescription); 
    }]; 
    [task resume]; 
} 
+0

感谢,但如何与NSURLSession实施进展块? – Nuibb

+0

以及我可以使用此NSURLSession块下载时做任何依赖项?我的意思是同步一个又一个? – Nuibb

+0

雅我正在努力实施NSProgress块。在你的代码中,我收到了“发送'void(^)(NSProgress * __ strong)'到不兼容类型参数NSProgress * __ autoreleasing _Nullable * _Nullable'”的错误。如何解决这个问题?以及如何将孩子NSProgress聚合到一个主NSProgress中? – Nuibb