How to find and cancel a task in NSURLSession? How to find and cancel a task in NSURLSession? ios ios

How to find and cancel a task in NSURLSession?


To get tasks list you can use NSURLSession's method

- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks))completionHandler;

Asynchronously calls a completion callback with all outstanding data, upload, and download tasks in a session.

Then check task.originalRequest.URL for returned tasks to find the one you want to cancel.


Based on all the answers below, I'd go for something like this:

Swift 5

 func cancelTaskWithUrl(_ url: URL) {    URLSession.shared.getAllTasks { tasks in      tasks        .filter { $0.state == .running }        .filter { $0.originalRequest?.url == url }.first?        .cancel()    }  }

You also probably want to account for your task completion handler, since canceling the task will result Error in that completion handler.


Hope below code help.

-(IBAction)cancelUpload:(id)sender {        if (_uploadTask.state == NSURLSessionTaskStateRunning) {        [_uploadTask cancel];     }  }