Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and cancel a task in NSURLSession?

I'm using an NSURLSession object to load images in my application. That could be loading several images simultaneously.

In some moments I need to cancel the loading of one specific image and continue loading others.

Could you suggest the correct way to do that?

like image 978
Rostyslav Druzhchenko Avatar asked May 07 '14 13:05

Rostyslav Druzhchenko


People also ask

How do I use NSURLSession in Objective C?

NSURLSession introduces a new pattern to Foundation delegate methods with its use of completionHandler: parameters. This allows delegate methods to safely be run on the main thread without blocking; a delegate can simply dispatch_async to the background, and call the completionHandler when finished.

What are the types of NSURLSession?

Types of URL Session TasksData tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server. Upload tasks are similar to data tasks, but they also send data (often in the form of a file), and support background uploads while the app isn't running.

What is NSURLSession daemon?

The NSURLSession Daemon (nsurlsessiond) is used for uploading and downloading content. Apps can delegate transfers to the daemon which continues the transfer even after the delegating app quits. So it could be any application. It's not restricted to Apple apps and services, all apps can use this daemon.


2 Answers

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.

like image 72
Avt Avatar answered Sep 30 '22 16:09

Avt


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.

like image 40
inokey Avatar answered Sep 30 '22 17:09

inokey