如何用AFURLSessionManager取消NSURLSessionDownloadTask?

时间:2014-12-02 05:04:52

标签: ios afnetworking nsurlsessiondownloadtask

我想在方法@selector(collectionAction)中使用AFURLSessionManager下载一些图片:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
  for (int i = 0; i < _collectionArr.count; ++i) {

    NSURL *URL = [NSURL URLWithString:URL_ADDRESS(portNumber,_collectionArr[i])];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

        NSLog(@"File downloaded to: %@", filePath);
        if (!filePath) {
            [manager invalidateSessionCancelingTasks:YES];
//          [manager.operationQueue cancelAllOperations];

            [self performSelector:@selector(collectionAction) withObject:nil afterDelay:REQUEST_AGAIN_TIME];
            return ;
        }
        if (i == _collectionArr.count - 1) {
            [SVProgressHUD showImage:nil status:@"Done"];
        }

    }];
    [downloadTask resume];
}

如果任务失败,它将自动执行选择器[self performSelector:@selector(collectionAction) withObject:nil afterDelay:REQUEST_AGAIN_TIME]; 如果我什么也不做这样的输出

2014-12-02 11:34:09.711 MoneyPower[11216:1204579] File downloaded to: (null)
2014-12-02 11:34:12.936 MoneyPower[11216:1204579] File downloaded to: (null)
2014-12-02 11:34:12.951 MoneyPower[11216:1204579] File downloaded to: (null)

并且数字正在滚动和滚动,然后我的iPhone几乎停止工作。因此,如果任何这些任务失败,我想取消任务。但是[manager invalidateSessionCancelingTasks:YES];[manager.operationQueue cancelAllOperations];我有另一个错误

2014-12-02 11:34:13.040 MoneyPower[11216:1204788] *** Terminating app due to uncaught     exception 'NSInternalInconsistencyException', reason: 'An instance 0x17947310 of class __NSCFLocalDownloadTask was deallocated while key value observers were still registered with it. Current observation info: <NSKeyValueObservationInfo 0x179449e0> (<NSKeyValueObservance 0x17944b40: Observer: 0x1785d3a0, Key path: state, Options: <New: YES, Old: YES, Prior: NO> Context: 0x3992cc, Property: 0x179462a0>)'
*** First throw call stack:(0x227ddc1f 0x2ffc4c8b 0x227ddb65 0x23485c25 0x2ffded5f 0x2229cb89 0x2ffded5f 0x3055fae1 0x3055fae1 0x836e29 0x8312c9 0x838567 0x839891 0x30685e31 0x30685b84)libc++abi.dylib: terminating with uncaught exception of type NSException

我该如何处理?

0 个答案:

没有答案