translation
Using Touch ID and Face ID with SwiftUI


More content welcome to follow the public account “Swift Garden”

Most Apple devices have biometric authentication, including fingerprint and facial recognition to unlock them. This feature is also available to developers, which means we can use it to ensure that sensitive data can only be read by legitimate users.

This is yet another Objective-C API, but it’s just slightly unpleasant to use with SwiftUI, and better than the other frameworks we’ve looked at so far.

Before we write the code, you need to add a new key to your info.plist file that explains to the user why you need to access Face ID. The reason for the Touch ID request is in the code, while the reason for the Face ID request is in the info.plist.

Open info.plist, right-click in a blank area, and select Add Row. Scroll through the list until you find “privacy-face ID Usage Description” and then fill in the value “We need to unlock your data.”

Go back to contentView.swift and add this line to the file header:

import LocalAuthenticationCopy the code

Ok, now you can use the biometrics API. The usage mentioned above is a bit tricky for this reason: The Swift developers use the Error protocol to represent various errors at runtime, whereas Objective-C uses a class called NSError to handle them. Since this is an Objective-C API, we need to handle the problem with NSError, passing the value with am&, like an inout parameter.

We’ll write a authenticate() method and put all the biometric authentication code there. There are four steps:

  1. createLAContextExample so that we can query the availability of biometric features, as well as perform identification detection.
  2. The reason to check for biometrics is because some iOS devices, like the iPod Touch, don’t have Touch ID or Face ID.
  3. If biometric identification is possible, we make the actual identification request and pass in a closure to be called when the identification is complete.
  4. Our completion closure code is called whether the recognition passes or not. Since it is not executed on the main thread, we need to push the UI-related work back to the main thread.

Add the following method to the ContentView:

func authenticate(a) {
    let context = LAContext(a)var error: NSError?

    // Check whether biometric identification can be performed
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        // Perform identification if possible
        let reason = "We need to unlock your data."

        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, authenticationError in
            // The authentication is complete
            DispatchQueue.main.async {
                if success {
                    // Authentication succeeded
                } else {
                    // Authentication failed}}}}else {
        // There is no biometric fingerprint}}Copy the code

This method doesn’t do much on its own because it’s not connected to SwiftUI yet. To fix this problem, we add a state that changes when authentication is complete. And enclose the authentication method in onAppear().

@State private var isUnlocked = falseCopy the code

This state determines whether to display data and changes to true if authentication succeeds. Replace the above // authentication success comment with the following code:

self.isUnlocked = trueCopy the code

Finally, add the initial UI to the body property like this:

VStack {
    if self.isUnlocked {
        Text("Unlocked")}else {
        Text("Locked")
    }
}
.onAppear(perform: authenticate)Copy the code

If you’re running your app in an emulator, you’ll see “Locked.” This is because the emulator is not configured for biometrics by default, and we didn’t print an error message, so it silently failed.

To test Face ID, go to the Hardware menu and select Face ID > Weekly, then restart the app. You’ll be presented with a Face ID prompt, which can be checked or failed by selecting Face ID > Matching Face or non-matching Face from the Hardware menu.

When the Face ID test passes, the actual functions of our app can be used.


My official account here Swift and computer programming related articles, as well as excellent translation of foreign articles, welcome to pay attention to ~