NSURLSession cancel Task

回眸只為那壹抹淺笑 提交于 2019-12-03 20:19:44

问题


I create new NSURLSession with following configs

 if (!self.session) {
            NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:[self uniquieIdentifier]];
            config.discretionary = NO;
            self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        }

and on after pressing a button I am trying to stop all current download tasks.

[[[self session] delegateQueue] setSuspended:YES];
[[self session] invalidateAndCancel];

Nevertheless I get responses in delegate method didFinishDownloadingToURL, and I am pretty sure that no new sessions or download task are created after this point. How to stop all task from happening?


回答1:


I do not reccommend to use invalidateAndCancel method cause the queue and its identifier keeps invalidated and cannot be reused untill you reset the whole device.

NSURLSession class reference

I use this code to cancel all pending tasks.

- (void) cancelDownloadFiles
{

    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {

        for (NSURLSessionTask *_task in downloadTasks)
        {
            [_task cancel];

            id<FFDownloadFileProtocol> file = [self getFileDownloadInfoIndexWithTaskIdentifier:_task.taskIdentifier];

            [file.downloadTask cancel];

            // Change all related properties.
            file.isDownloading = NO;
            file.taskIdentifier = -1;
            file.downloadProgress = 0.0;

        }

    }];

    cancel = YES;
}



回答2:


That is the expected behaviour, when you cancel tasks on a session they might still call the delegate method.

Have you check the state of the given task? It should be NSURLSessionTaskStateCanceling.



来源:https://stackoverflow.com/questions/19975642/nsurlsession-cancel-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!