How to find and cancel a task in NSURLSession?

Rostyslav Druzhchenko picture Rostyslav Druzhchenko · May 7, 2014 · Viewed 31.1k times · Source

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?

Answer

Avt picture Avt · May 7, 2014

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.