iOS_Subhra
7/4/2018 - 5:40 AM

Touch ID

Code Snippet for Touch ID

import LocalAuthentication

//use the call method below with the user’s email as account and password when the user signs up and logs in.

fileprivate func saveAccountDetailsToKeychain(account: String, password: String) {

      guard account.isEmpty, password.isEmpty else { return }
      UserDefaults.standard.set(account, forKey: "lastAccessedUserName")
      
      let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: account, accessGroup: KeychainConfiguration.accessGroup)
      do {
         try passwordItem.savePassword(password)
      } catch {
         print("Error saving password")
     }
}

override func viewDidAppear(_ animated: Bool) {
   super.viewDidAppear(animated)
   authenticateUserUsingTouchId()
}

fileprivate func authenticateUserUsingTouchId() {
    let context = LAContext()
    if context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthentication, error: nil) {
        self.evaulateTocuhIdAuthenticity(context: context)
    }
}

func evaulateTocuhIdAuthenticity(context: LAContext) {
    guard let lastAccessedUserName = UserDefaults.standard.object(forKey: "lastAccessedUserName") as? String else { return }
    context.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: lastAccessedUserName) { (authSuccessful, authError) in
     if authSuccessful {
     
     self.loadPasswordFromKeychainAndAuthenticateUser(lastAccessedUserName)
         
    } else {
       if let error = authError as? LAError {
           showError(error: error)
      }
    }
  }
}

func showError(error: LAError) {
        var message: String = ""
        switch error.code {
        case LAError.authenticationFailed:
            message = "Authentication was not successful because the user failed to provide valid credentials. Please enter password to login."
            break
        case LAError.userCancel:
            message = "Authentication was canceled by the user"
            break
        case LAError.userFallback:
            message = "Authentication was canceled because the user tapped the fallback button"
            break
        case LAError.touchIDNotEnrolled:
            message = "Authentication could not start because Touch ID has no enrolled fingers."
            break
        case LAError.passcodeNotSet:
            message = "Passcode is not set on the device."
            break
        case LAError.systemCancel:
            message = "Authentication was canceled by system"
            break
        default:
            message = error.localizedDescription
            break
        }
        self.showPopupWithMessage(message)
    }
    
    fileprivate func loadPasswordFromKeychainAndAuthenticateUser(_ account: String) {
  guard !account.isEmpty else { return }
  let passwordItem = KeychainPasswordItem(service:   KeychainConfiguration.serviceName, account: account, accessGroup: KeychainConfiguration.accessGroup)
  do {
      let storedPassword = try passwordItem.readPassword()
      authenticateUser(storedPassword)
  } catch KeychainPasswordItem.KeychainError.noPassword {
      print("No saved password")
  } catch {
      print("Unhandled error")
  }
}