Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Alamofire stop all requests

Tags:

Is there any way I can for example say:

Alamofire.Manager.cancelAllRequests() or Alamofire.Manager.sharedInstance.cancelAllRequests()?

Of course it would be great if these requests especially in case of image download would only be paused for later when I'll cal the same URL but... I need at least to be able to cancel all requests at a global level. Some suggestions ?

In my app I have a wrapper above the Alamofire.request(.Post....) way of doing things so I would really appreciate not making me create or interact with Manager class in another way besides that specified above.

like image 747
Fawkes Avatar asked Oct 07 '15 18:10

Fawkes


People also ask

How do I cancel a previous request in Swift?

If you want to cancel the request, you need to trace the requests made and try to cancel it. You can store it in an array and cancel every previous request stored. In your code you create a request: let request = Alamofire.


1 Answers

cnoon's one-liner solution is great but it invalidates the NSURLSession and you need to create a new one.

Another solution would be this (iOS 7+):

session.getTasks { dataTasks, uploadTasks, downloadTasks in     dataTasks.forEach { $0.cancel() }     uploadTasks.forEach { $0.cancel() }     downloadTasks.forEach { $0.cancel() } } 

Or if you target iOS 9+ only:

session.getAllTasks { tasks in     tasks.forEach { $0.cancel() } } 
like image 71
ldiqual Avatar answered Sep 19 '22 18:09

ldiqual