Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 get error code from error

Tags:

ios

swift

I have a variable that is defined like as an Error and this is what it looks like when I print it:

Optional(Error Domain=com.apple.LocalAuthentication Code=-2 "Canceled by user." UserInfo={NSLocalizedDescription=Canceled by user.})

What I am trying to do is get that Code of -2...how would I do that?

like image 881
user979331 Avatar asked Jun 07 '18 17:06

user979331


3 Answers

You can unwrap the optional error first and compare the -2 case.

if let error = error {
   switch error._code {
      case LAError.userCancel.rawValue: // or -2 if you want
        // do something
      default:
        break
   }
}
like image 97
Calvin Avatar answered Oct 19 '22 17:10

Calvin


I wrote this small extension:

extension Error {
    var errorCode:Int? {
        return (self as NSError).code
    }
}

Using:

if error.errorCode == -2 {
    //some code
}
like image 30
dr OX Avatar answered Oct 19 '22 16:10

dr OX


You just need to cast your Error to LAError (Local Authentication error) and switch its code property:

if let error = error as? LAError {
    switch error.code {
    case .userCancel:
        print("userCancel")
    default:
        print("unknown error")
    }
}
like image 3
Leo Dabus Avatar answered Oct 19 '22 16:10

Leo Dabus