Error handling for cancelled request

Viewed 7138

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?

5 Answers

You can achieve it by this genric approach

if let errorCode = (error.underlyingError as NSError?)?.code, errorCode == NSURLErrorCancelled { // for cancelled 

Should be now:

var isCancelError: Bool {
    guard let afError = self as? AFError else { return false }
    return afError.isExplicitlyCancelledError
}
Related