0
0
iOS Swiftmobile~20 mins

Biometric authentication (Face ID, Touch ID) in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
Build: BiometricAuthScreen
This screen lets users authenticate using Face ID or Touch ID. It shows a button to start authentication and displays success or error messages.
Target UI
-------------------------
| Biometric Authentication |
|-------------------------|
|                         |
|   [ Authenticate ]       |
|                         |
| Status:                 |
|                         |
-------------------------
Add a button labeled 'Authenticate' centered on the screen.
When tapped, start biometric authentication using Face ID or Touch ID.
Show a status message below the button: 'Authentication succeeded' or 'Authentication failed' or error message.
Handle cases where biometrics are not available or not enrolled.
Use LocalAuthentication framework.
Starter Code
iOS Swift
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()
    }
}
Task 1
Task 2
Task 3
Task 4
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------------
| Biometric Authentication |
|-------------------------|
|                         |
|   [ Authenticate ]       |
|                         |
| Status:                 |
| Authentication succeeded |
-------------------------
User taps 'Authenticate' button.
System shows Face ID or Touch ID prompt.
If user authenticates successfully, status changes to 'Authentication succeeded'.
If authentication fails or is canceled, status changes to 'Authentication failed' or shows error message.
If biometrics are unavailable, status shows 'Biometric authentication not available or not enrolled'.
Stretch Goal
Add a toggle to switch between Face ID and passcode fallback authentication.
💡 Hint
Use LAContext's deviceOwnerAuthentication policy to allow passcode fallback when biometrics fail or are unavailable.