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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With