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