Getting started with FaceID/TouchID and LocalAuthentication using Swift

Since 2013, all iPhones have been launched with some sort of biometric sensors. From iPhone 5s to iPhone 8, Apple embedded a Touch ID sensor in the home button and from iPhone X onwards they started using Face ID to detect user’s face before unlocking the device.

Apple provides APIs for developers to use these security features in their apps as well. Today I will talk about how to go about setting up biometric security features in your iOS app.

Before starting, make sure you open Info.plist file in Xcode and enter a new row for key “NSFaceIDUsageDescription” and enter a string value for this key. The value should talk about the reason you are using Face ID.

For Touch ID users, the reason is added within the code itself and you don’t need to do it in Info.plist.

Make sure you import LocalAuthentication framework.

So you first do this:

import LocalAuthentication
let context = LAContext()
    var error: NSError?
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        let reason = "Touch ID identification needed" // For touch ID only

        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) {
            [weak self] success, authenticationError in

            DispatchQueue.main.async {
                if success {
                    // success 
                } else {
                    // error
                }
            }
        }
    } else {
        // no biometry on your device
    }

 

So we are first creating an instance of LAContext() and ¬†checking if the user’s device even has biometry (Touch ID or Face ID).

If yes, then the system checks if the Face ID or Touch ID is correctly identified and verified. If this is the case we get in to the closure with two parameters – “success” and “authenticationError“. ¬†We can use success bool value to then execute any code that we want to get executed if the Face ID / Touch ID has worked correctly. If the Touch ID or Face ID thinks the input is wrong then we can do any error handling inside else block.

Make sure that what ever UI based code you execute, should be done on main thread. Therefore, we are using DspatchQueue.main.async {} when executing the if – else statement.
That’s about it! In order to test Face ID /Touch ID in Xcode Simulator – go to Hardware -> TouchID/FaceID -> Enrolled State. Then when your app asks you for identification, head back to Hardware -> Touch ID/FaceID -> Matching or non Matching to test our the above code.

Leave a Reply

Your email address will not be published. Required fields are marked *