Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling for cancelled request

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.

  1. Check the condition if the error is created due to request cancel
  2. Check if the viewController is alive
  3. Also I can set a Bool variable in viewWillDisappear, which is a simple solution

How to handle the situation?

Also how to check point 1 & 2?

like image 775
iOS Avatar asked Mar 23 '16 16:03

iOS


People also ask

What does it mean when a request is Cancelled?

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.

Which return code indicates that a user cancellation?

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.


2 Answers

This is a more generic approach which works for any device language:

Swift 4

if (response.error as NSError?)?.code == NSURLErrorCancelled {
   // Do Your stuff
}
like image 181
aumanets Avatar answered Oct 06 '22 03:10

aumanets


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.

like image 37
Cerlin Avatar answered Oct 06 '22 01:10

Cerlin