I use Alamofire
to send a download request. I am handling Success
and Failure
cases as shown below.
Alamofire.request {
case Success:
// Update UI
case Failure:
// Show Alert message (error!.localizedDescription)
}
Everything is perfectly fine.
When I go back, in viewWillDisappear
, I cancel any ongoing request. The issue is, canceling the request throws the error message and that triggers the alert when I am not on that screen.
To my knowledge, I can take two actions.
viewController
is aliveBool
variable in viewWillDisappear
, which is a simple solutionHow to handle the situation?
Also how to check point 1 & 2?
1 verb If you cancel something that has been arranged, you stop it from happening. If you cancel an order for goods or services, you tell the person or organization supplying them that you no longer wish to receive them.
499 Client Closed Request Used when the client has closed the request before the server could send a response. 444 No Response Used to indicate that the server has returned no information to the client and closed the connection.
This is a more generic approach which works for any device language:
Swift 4
if (response.error as NSError?)?.code == NSURLErrorCancelled {
// Do Your stuff
}
NOTE: Use aumanets
answer for failsafe check
For the ppl who are wondering how to use the option 1
you can check the request cancelled error to find if the request is cancelled
let errorDict = (error as NSError).userInfo;
if let errorString = errorDict["NSLocalizedDescription"] as? String, errorString == "cancelled" {
// Request is cancelled.
}
This answer is derived from @peres's answer.
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