Swift version: 5.10
Face ID offers a secure and convenient method for users to authenticate themselves using facial recognition. Just like Touch ID, Face ID leverages the biometric information registered on the device. Importantly, your app cannot access these facial data directly, ensuring privacy and security.
Prerequisites
Before getting started, you need to import the LocalAuthentication framework:
Copied!import LocalAuthentication
When using Face ID, there are several potential outcomes you need to handle:
• The device may not support Face ID.
• The device supports Face_ID, but it has not been configured by the user.
• The user fails authentication, perhaps due to misalignment or choosing a different authentication method, like a passcode.
Remember, Apple mandates that apps provide an alternative authentication method in case Face_ID is unavailable or fails, like a passcode entry.
The core part of using Face_ID authentication looks like this:
Copied!func authenticateUser() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "Please authenticate using Face ID." context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in DispatchQueue.main.async { if success { self.runSecureAction() } else { let ac = UIAlertController(title: "Authentication Failed", message: "Sorry, we couldn't authenticate you.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) self.present(ac, animated: true) } } } } else { let ac = UIAlertController(title: "Face ID Not Available", message: "Your device is either not configured for Face ID or doesn't support it.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }
This function performs the following:
• Checks if Face_ID is available and configured on the device.
• Prompts the user to authenticate using Face_ID.
• Handles both successful and failed authentication attempts.
You can further customize the action inside runSecureAction() and show appropriate error messages based on the failure scenario.