如何通过NSOperationQueue从多个URL下载多个文件

时间:2015-12-13 08:02:30

标签: ios objective-c afnetworking-2 nsoperationqueue afhttprequestoperation

我正在努力使用AFNetworking为多个文件实现下载机制。我想从多个url一个接一个地下载zip文件,带有进度消息。我试着跟随代码,但得到错误 -

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

请帮忙。

1 个答案:

答案 0 :(得分:3)

当您致电GET时,它已添加到operationQueue的{​​{1}}。所以不要再将它添加到队列中。

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

此代码还存在其他问题,但我建议您转换为使用AFHTTPRequestOperationManager的{​​{1}},而不是尝试解决所有这些问题。旧的AFHTTPSessionManager基于NSURLSession,但AFHTTPRequestOperationManager现已弃用。事实上,AFNetworking 3.0已完全退役NSURLConnection

因此,NSURLConnection可能看起来像:

AFHTTPRequestOperationManager