Touch ID Verification in SwiftUI with iOS using Swift 5: A Step-by-Step Guide

🎯 Introduction

In iOS, Face ID and Touch ID are secure and familiar authentication methods that users trust. In this blog post, we will explore how to implement Touch ID verification in SwiftUI using the latest Swift 5 language. We'll walk through the process step-by-step, providing code examples and explanations along the way.

Prerequisites:

Before we begin, make sure you have the following:

Step 1: Import LocalAuthentication

The first step is to import the LocalAuthentication framework into your SwiftUI view or class. This framework provides the necessary APIs for working with biometric authentication.

swift

import LocalAuthentication

Step 2: Create an LAContext

Next, we need to create an instance of LAContext, which will be responsible for handling the authentication process.

swift

let context = LAContext()

Step 3: Perform Touch ID Verification

Now, let's implement the Touch ID verification logic. We'll use the evaluatePolicy(_:localizedReason:reply:) method of the LAContext class to perform the authentication.

swift


context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Authentication") { success, error in

    DispatchQueue.main.async {

        if success {

            // User authenticated successfully, take appropriate action

            print("Awesome!! User authenticated successfully")

        } else {

            // User did not authenticate successfully, look at error and take appropriate action

            if let error = error as NSError? {

                print("Sorry!! Failed to authenticate: \(error.localizedDescription)")

            }

        }

    }

}

Step 4: Handling Unsupported Devices

It's important to handle cases where biometric authentication is not available on the user's device. We can use the canEvaluatePolicy(_:error:) method to check if the device supports biometric authentication.

swift


guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) else {

    print("Sorry!! This device does not support biometric authentication.")

    // Handle the lack of support

    return

}

Step 5: Putting It All Together - TouchIDVerify Class

To encapsulate the Touch ID verification logic, let's create a separate class called TouchIDVerify.


swift


import LocalAuthentication


class TouchIDVerify {


    static func verify(onSuccess: @escaping (Bool) -> Void) {

        let context = LAContext()

        

        guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) else {

            print("Sorry!! This device does not support biometric authentication.")

            onSuccess(false)

            return

        }

        

        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Authentication") { success, error in

            DispatchQueue.main.async {

                if success {

                    // User authenticated successfully, take appropriate action

                    print("Awesome!! User authenticated successfully")

                    onSuccess(true)

                } else {

                    // User did not authenticate successfully, look at error and take appropriate action

                    if let error = error as NSError? {

                        print("Sorry!! Failed to authenticate: \(error.localizedDescription)")

                    }

                    onSuccess(false)

                }

            }

        }

    }

}

Step 6: Implementing Touch ID Verification

To use the TouchIDVerify class, you can call the verify method from a button action or viewDidLoad in your SwiftUI view.


swift


TouchIDVerify.verify { result in

    if result {

        // Success action

        print("Authentication succeeded")

    } else {

        // Failure action

        print("Authentication failed")

    }

}

In this blog post, we have learned how to implement Touch ID verification in SwiftUI using Swift 5. By following the step-by-step guide, you can add a secure and familiar authentication method to your iOS applications. Touch ID verification provides a seamless and user-friendly experience for your users, enhancing the security of your app.