------------------------- | Biometric Authentication | |-------------------------| | | | [ Authenticate ] | | | | Status: | | | -------------------------
Biometric authentication (Face ID, Touch ID) in iOS Swift - Mini App: Build & Ship
import SwiftUI import LocalAuthentication struct BiometricAuthScreen: View { @State private var statusMessage = "" var body: some View { VStack(spacing: 20) { // TODO: Add Authenticate button here // TODO: Show statusMessage text here } .padding() } } struct BiometricAuthScreen_Previews: PreviewProvider { static var previews: some View { BiometricAuthScreen() } }
import SwiftUI import LocalAuthentication struct BiometricAuthScreen: View { @State private var statusMessage = "" var body: some View { VStack(spacing: 20) { Button("Authenticate") { authenticateUser() } .padding() .background(Color.blue) .foregroundColor(.white) .cornerRadius(8) Text(statusMessage) .foregroundColor(.gray) .multilineTextAlignment(.center) .padding(.horizontal) } .padding() } func authenticateUser() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { let reason = "Please authenticate to continue." context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in DispatchQueue.main.async { if success { statusMessage = "Authentication succeeded" } else { if let error = authenticationError { statusMessage = error.localizedDescription } else { statusMessage = "Authentication failed" } } } } } else { DispatchQueue.main.async { if let error = error { statusMessage = error.localizedDescription } else { statusMessage = "Biometric authentication not available or not enrolled" } } } } } struct BiometricAuthScreen_Previews: PreviewProvider { static var previews: some View { BiometricAuthScreen() } }
This solution uses SwiftUI to create a simple screen with a button labeled Authenticate. When the user taps the button, the authenticateUser() function runs.
Inside authenticateUser(), we create an LAContext object to check if biometric authentication is available and enrolled on the device.
If biometrics are available, we call evaluatePolicy to prompt the user for Face ID or Touch ID. The result is handled asynchronously, updating the statusMessage state to show success or failure.
If authentication fails, we show the error message if available, otherwise a generic failure message.
If biometrics are not available or not enrolled, we update the status message accordingly, showing the error description if available.
The UI updates automatically because statusMessage is a @State variable, and the text below the button shows the current status.
------------------------- | Biometric Authentication | |-------------------------| | | | [ Authenticate ] | | | | Status: | | Authentication succeeded | -------------------------