iOS Alamofire stop all requests
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.
How to cancel all requests in Alamofire's shared manager
Use NSURLSession
's invalidateAndCancel
method:
manager.session.invalidateAndCancel
Cancel a request Alamofire
Alamofire 4 / Swift 3 / Xcode 8
You can cancel a single request as below:
1 - First get the request:
let request = Alamofire.SessionManager.default.request(path!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: createHeader()).responseJSON { response in
switch response.result {
case .success(let data):
success(data as AnyObject?)
case .failure(let error) :
failure(error as NSError)
}
}
2 - Then, in your viewDidDisappear, just call:
request.cancel()
You can cancel all requests as below:
Alamofire.SessionManager.default.session.getTasksWithCompletionHandler { (sessionDataTask, uploadData, downloadData) in
sessionDataTask.forEach { $0.cancel() }
uploadData.forEach { $0.cancel() }
downloadData.forEach { $0.cancel() }
}
How could I cancel several requests with Alamofire?
You can write something like this to cancel specific task if you know request or url
func cancellRequest(for request: URLRequest) {
Alamofire.SessionManager.default.session.getAllTasks { (tasks) in
_ = tasks
.filter({ $0.originalRequest?.url?.path == request.url?.path })
.map({ $0.cancel() })
}
}
Alamofire cancel a request out of multiple requests
According to the documentation cancel would:
Cancels the underlying task, producing an error that is passed to any registered response handlers.
Therefore, add a response handler to your request and see whether error messages are passed to them. If so, it means that the cancel operates correctly.
Related Topics
How to Make Uiimageview Automatically Resize to the Size of the Image Loaded
How to Move Cursor from One Text Field to Another Automatically in Swift iOS Programmatically
Hide Navigationbar When Scrolling Tableview in Collectionview
Run a Swift 2.0 App Forever in Background to Update Location to Server
How to Create and Send the JSON Data to Server Using Swift Language
How to Get the Build Uuid in Runtime and the Image Base Address
Limit Uitextfield Input to Numbers in Swift
Ios: How to Copy HTML into the Cut-Paste Buffer
How to Find Indexpath for Tapped Button in Tableview Using Seque
iPhone Uitextfield Background Color
Remove Uisegmentedcontrol Separators Completely. (Iphone)
How to Check Whether iPhone and Apple Watch Are Connected
What Does It Mean to "Weak-Link" a Framework
How to Hide First Section Header in Uitableview (Grouped Style)
How to Change Color of Uitableviewcell When Selecting