NSURLSession cancellation task

I am creating a new NSURLSession with the following configurations

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

and after clicking the button, I try to stop all current download tasks.

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

However, I get the answers in the didFinishDownloadingToURL delegate method, and I'm sure no new sessions or load task are created after that. How to stop all tasks?

+4
source share
2 answers

I do not recommend using the invalidateAndCancel method, because the queue and its identifier remain invalid and cannot be reused before you reset the entire device.

Class reference NSURLSession

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;
}
+14
source

, , .

? NSURLSessionTaskStateCanceling.

+2

All Articles