Add FaceID & TouchID to your iOS App (Swift)

Jigyasaa Alemu Sood
The SDCoders
Published in
4 min readApr 28, 2021

To log our users into our apps, users often have to enter their usernames and passwords. This is a common approach used in nearly all software platforms.

In iOS, we can take advantage of biometrics — unique personal identifiers a user has (like a fingerprint or facial appearance) to authenticate or verify a user’s identity. Touch ID authenticates a user using their fingerprints and Face ID authenticates via a user’s facial appearance.

The iOS framework for this functionality is called LocalAuthentication. Let see how this works!

Steps:

  1. Add login button to ViewController
  2. Import the LocalAuthentication framework
  3. Check if the device is capable of using biometrics, if the sensor is present and the setting is enabled by the user
  4. If enabled, send a request to the user
  5. If the request is successful, this is the device’s owner and we can unlock the app
  6. Otherwise — send a failure message

First, let’s set up the UI on the Main.storyboard

Add a button to your login page

Then add an ibaction for that button, which runs every time you click on the button:

Create a segue from the login ViewController to your app’s first screen’s ViewController

Now let’s add some code to the ViewController.swift file that is connected to the Login page

let’s import the LocalAuthentication framework, which stores the biometric functionality we want to tap into:

import LocalAuthentication

We will design a function called authenticate() to perform the authentication. It will store a context of type LAContext and hold an error of NSError? If something goes wrong, the error will contain a message of what went wrong.

@IBAction func didTapLoginBtn(_ sender: Any) {    authenticate()}func authenticate() {    let context = LAContext()    var error: NSError? = nil  if        context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {   let reason = "Identify yourself!"   context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics,                          localizedReason: reason) {       [weak self] success, authenticationError in       DispatchQueue.main.async {          guard success, error == nil else{          //Authentication failed, prompt an error message to the    
//user
return } //Authentication successful! Proceed to next app screen. self?.performSegue(withIdentifier: "loginSegue", sender: nil) } }} else {//No biometrics availablelet alert = UIAlertController(title: "Unavailable", message: "FaceID Auth not available", preferredStyle: .alert)alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil))present(alert, animated: true)}}

context.evaluatePolicy() will have a closure that contains the parameters of success and authenticationError. Since it takes a few seconds to take a user’s biometrics to identify them, this is an asynchronous action so we need to use DispatchQueue to send this task to the async thread.

Check the success and authenticationError condition of context.evaluatePolicy() and perform whatever behavior we want within the closure.

This approach works for Touch ID and Face ID.

One last step in order to make the code work is to add permission for FaceID in the info.plist file. Go to Info.plist and add a key for Privacy — Face ID Usage Description. This will take the form of the reason provided to the user within Face ID, instead of using the reason in our closure.

Running on a simulator

When you first run your app and press the login button, you might see an error message like so:

To fix this, just make sure to check “Enrolled” in order to allow faceID on simulator

Once you do that, when you click login again, it should prompt you to use faceID!

You can go back to the simulator’s nav bar and test if faceID is working by clicking Matching face and non-matching face after you click on the login button.

Upon successful login, I see my app’s main screen!

That’s it! Quick and easy tutorial on how to implement FaceID and TouchID for iOS apps, hope you liked it :)

--

--

Jigyasaa Alemu Sood
The SDCoders

Software Engineer | App Developer | Entrepreneur | TA @ CodePath