取消正在等待的下载任务

时间:2017-05-23 05:22:10

标签: ios xcode nsurlsessiondownloadtask nsurlsessiontask

我有两个视图控制器 控制器A和控制器B

在控制器A中,我有一个按钮来显示视图控制器B.

在控制器B中,我有一个按钮下载(下载以下代码开始)和后退按钮(关闭视图控制器B以返回A)

现在我希望每当我从控制器B返回到控制器A,并再次从控制器A返回到控制器B时,所有待处理的下载任务都将被取消。

我尝试添加代码,在视图中加载

[dataTask suspend];
[dataTask cancel];

但除此之外,还会收到当前正在运行的下载字节

  - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data

我使用下面的代码下载多个文件

@property (nonatomic, retain) NSMutableData *dataToDownload;
@property (nonatomic) float downloadSize;
@property (nonatomic, retain)NSURLSessionDownloadTask *dataTask;
- (void)viewDidLoad {
    [super viewDidLoad];

for(int i=0;i<[urlarray count];i++)
{
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

    NSURL *url = [NSURL URLWithString: [urlarray objectAtIndex:i]];
    dataTask = [defaultSession downloadTaskWithURL: url];

    [dataTask resume];
}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    completionHandler(NSURLSessionResponseAllow);

    progressBar.progress=0.0f;
    _downloadSize=[response expectedContentLength];
    _dataToDownload=[[NSMutableData alloc]init];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    [_dataToDownload appendData:data];
    progressBar.progress=[ _dataToDownload length ]/_downloadSize;
}

1 个答案:

答案 0 :(得分:1)

所以在我的记忆中,我取消了下面的下载任务。

    NSURLSession *session = [SingletonManager sharedInstance].downloadSession;

    [session
        getTasksWithCompletionHandler:^(
            NSArray<NSURLSessionDataTask *> *_Nonnull dataTasks,
            NSArray<NSURLSessionUploadTask *> *_Nonnull uploadTasks,
            NSArray<NSURLSessionDownloadTask *> *_Nonnull downloadTasks) {

          for (NSURLSessionTask *task in downloadTasks) {
              [task cancel];
              [session invalidateAndCancel];
              NSLog(@"Download session %@ will be invalidate and cancel",
                    session);
             [SingletonManager sharedInstance].downloadSession = nil;
          }
        }];
  

[session invalidateAndCancel];

意味着让这个会话无效并立即取消

  

[session finishTasksAndInvalidate]

意味着等到这个任务完成后再加密所有任务。