Как скачать несколько файлов с нескольких URL-адресов по NSOperationQueue
Я изо всех сил пытаюсь реализовать механизм загрузки для нескольких файлов с использованием AFNetworking. Я хочу скачать ZIP-файл один за другим из нескольких URL с сообщением о прогрессии. Я пытался как следующий код, но получаю ошибку как -
*** 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 ответ
Когда вы звоните GET
уже добавлено в operationQueue
из AFHTTPRequestionOperationManager
, Так что не добавляйте его в очередь снова.
Кроме того, вы должны создать экземпляр 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];
}