Swift version: 5.10
Touch ID is an easy and secure way for users to authenticate themselves, which is why it has become so popular among apps. When using Touch ID, authentication is done using fingerprints registered by the user, and your app never has direct access to those fingerprints. This ensures both security and a seamless user experience.
Prerequisites
To get started, you need to import the LocalAuthentication framework:
Copied!import LocalAuthentication
The authentication process can result in several possible scenarios that you need to handle:
• The device might not support Touch ID.
• The device supports Touch ID, but it has not been configured.
• The user might fail authentication, either due to an incorrect fingerprint or by choosing to enter a passcode instead.
Apple requires that your app provides an alternative authentication method, such as a passcode. Unfortunately, you need to request and store this passcode yourself, as Apple does not provide access to the system unlock code.
The core part of using Touch ID authentication is implemented as follows:
Copied!func authenticateUser() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "Identify yourself!" context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in DispatchQueue.main.async { if success { self.runSecretCode() } else { let ac = UIAlertController(title: "Authentication failed", message: "Sorry!", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) self.present(ac, animated: true) } } } } else { let ac = UIAlertController(title: "Touch ID not available", message: "Your device is not configured for Touch ID.", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }
This code checks whether the device supports Touch ID and, if so, prompts the user to authenticate. If authentication is successful, it proceeds with a secured action; otherwise, it informs the user of the failure.