0

我正在努力使用 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];
    }
}

请帮忙。

4

1 回答 1

3

当您调用 时GET,它已经添加operationQueueAFHTTPRequestionOperationManager. 所以不要再次将其添加到队列中。

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


此代码还有其他问题,但与其尝试解决所有这些问题,我建议您过渡到AFHTTPSessionManager使用NSURLSession. 旧AFHTTPRequestOperationManagerNSURLConnection基于 -,但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];
}
于 2015-12-13T08:36:35.567 回答