iOS Alamofire stop all requests
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() }
}
You should use the NSURLSession
methods directly to accomplish this.
Alamofire.SessionManager.default.session.invalidateAndCancel()
This will call all your completion handlers with cancellation errors. If you need to be able to resume downloads, then you'll need to grab the resumeData
from the request if it is available. Then use the resume data to resume the request in place when you're ready.
Below Code stops the Requests in [Swift 3]:
Plus the code works for Alamofire v3 & v4 plus for iOS 8+.
func stopTheDamnRequests(){
if #available(iOS 9.0, *) {
Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
tasks.forEach{ $0.cancel() }
}
} else {
Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
sessionDataTask.forEach { $0.cancel() }
uploadData.forEach { $0.cancel() }
downloadData.forEach { $0.cancel() }
}
}
}
Simply Copy and paste the function.