iOS Alamofire Stop All Requests

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



Leave a reply



Submit