Overview
The LocalAuthentication package supports authentication in iOS apps
using either Face ID or Touch ID.
Setup
- Select the top entry in the Navigator.
- Under “TARGETS”, select the app target.
- Click the “Info” tab.
- Click the ”+” button to the right of the last key in the table.
- Enter the key “Privacy - Face ID Usage Description”.
- Enter a value that describes why Face ID is being used such as “We want to ensure that only you can view your data.”
Implementation
-
In the main view of the app add
import LocalAuthentication -
Add the following:
@State private var authenticated = false func authenticate() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, error: &error ) { let reason = "We want to ensure that only you can see your data." context.evaluatePolicy( .deviceOwnerAuthenticationWithBiometrics, localizedReason: reason ) { success, error in if success { authenticated = true } else { // The user did not authenticate. } } } else { // The device does not support biometrics. } } -
Add a call to
onAppearto the top View returned by thebodythat calls theauthenticatefunction..onAppear { authenticate() } -
Use the value of
authenticatedto decide what to render. -
Provide an alternate way for users to authenticate such as entering a username and password in case there are reasons they cannot currently use Face ID.
Testing in Simulator
To test in the Simulator, open the Simulator app and select Features … Face ID … Enrolled.
To simulate a successful Face ID scan, select Features … Face ID … Matching Face.
To simulate an unsuccessful Face ID scan, select Features … Face ID … Non-matching Face.