Search code examples
iosswiftswift3error-codetouch-id

"switch(error!.code)" in canEvaluatePolicy function does not exist in Swift 3 (Xcode 8)


I'm converting below code to Swift 3.

 if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error:nil) {

  // 2.
  context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics,
    localizedReason: "Logging in with Touch ID",
    reply: { (success : Bool, error : NSError? ) -> Void in

      // 3.
      dispatch_async(dispatch_get_main_queue(), {
        if success {
          self.performSegueWithIdentifier("dismissLogin", sender: self)
        }

        if error != nil {

          var message : NSString
          var showAlert : Bool

          // 4.
          switch(error!.code) {

Step 4 does not work anymore on Xcode 8, Swift 3. So I could not do the following cases:

switch(error!.code) {
          case LAError.AuthenticationFailed.rawValue:
            message = "There was a problem verifying your identity."
            showAlert = true
            break;

Currently, it's seems there was no solution that I could find yet. Any suggestion, please let me know.

Thanks a lot!


Solution

  • First change your reply closure of evaluatePolicy method, in Swift 3 it is Error not NSError.

    reply: { (success : Bool, error : Error? ) -> Void in
    

    Second, change performSegue with identifier like this.

    performSegue(withIdentifier: "dismissLogin", sender: self)
    

    In Swift 3 you need to convert Error object to NSError or use _code with Error instance instead of code.

    switch((error! as NSError).code)
    

    OR

    switch(error!._code)
    

    You need to also change you dispatch syntax like this.

    Dispatch.async.main {
        //write code
    }