How to implement biometric authentication on SwiftUI

Why should we secure our applications?

When you create and develop programs, you might find that users may need to use passwords on their iPhones or iPad to protect their data from other users.

It can become a hassle to create passwords and enter them whenever the user opens the application. So, why not use biometrics provided by Apple, which secure your iPhone or iPad as a whole, to access your device?

Biometric verification on Apple devices

With FaceID and TouchID on your application, the unnecessary hassle of having to use password lock is removed. This also promises more security due to the T1/T2 Apple Security Chip.

So, let’s use biometrics for our SwiftUI application.

Code

Step 1: Create a brand new SwiftUI, Xcode project.

Step 2: Now create any user interface, or copy-paste my code, which is as follows.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello User!")
        }
    }
}

Go to the Info.plist file, create a Privacy parameter, Privacy - Face ID Usage Description, and set its value to any desired reason.

Step 3: Now, create a function named authenticate(), which will be our biometrics authenticator. Remember to import LocalAuthentication as well.

import LocalAuthentication
func authenticate() {
    let context = LAContext()
    var error: NSError?
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        let reason = "We need to unlock your passwords."
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) {
            success, authenticationError in
           DispatchQueue.main.async {
                if success {
                    //Authentication Successful
                }
                else {
                    //Authentication Failed
                }
            }
        }
    }

    else {
        // No Biometrics found
    }
}

Step 4: Now, back in your view, create a State variable.

@State var isUnlocked = false

Step 5: Set its value to true when authentication is successful, and to false if authentication has failed, within the authenticate() function:

func authenticate() {
    ....
        if context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) {
            success, authenticationError in
            DispatchQueue.main.async {
                if success {
                    self.isUnlocked = true
                }
                else {
                    self.isUnlocked = false
                }
            }
        }
    ....
}

Step 6: Once the steps above are done, go back to your view and format it as follows.

struct ContentView: View {
    var body: some View {
        if isUnlocked {
            VStack {
                Text("Hello User!")
            }
        }
        else {
            Text("Use your biometrics to use the app.")
        }
    }
}

Step 7: Now tap into the .onAppear functionality of your ContentView file to load the authentication whenever the app loads.

struct ContentView: View {
    var body: some View {
        if isUnlocked {
            VStack {
                Text("Hello User!")
            }
        }
        else {
            Text("Use your biometrics to use the app.")
        }
    }
    .onAppear(perform: authenticate)
}

Step 8: Now, whenever your app loads, it will automatically prompt you for biometrics, and if successful, only you can see the actual screen.

The authentication code above works in the same manner for both FaceID and TouchID devices.

Free Resources