iOS集成FaceID或TouchID

1,225 阅读2分钟

前言

本文主要介绍iOS项目中如何集成FaceID和TouchID

官方API文档

说明

(1)iOS版本要求:

Touch ID要求 : iOS 8 以上

Face ID要求 : iOS 11 以上 (需使用者需同意开启 FaceID 权限)

(2)info.plist

需要在info.plist 加入NSFaceIDUsageDescription的key和value,来说明使用FaceID的用途。

(3)import LocalAuthentication框架

代码示例

集成FaceID和TouchID的代码相同

方法实现

import UIKit
import LocalAuthentication

class FaceIDAuth {
    class func startAuth(_ vc: UIViewController) {
        // 创建 LAContext 实例
        let context = LAContext()
        // 设置标题和声明接收返回错误的error
        context.localizedCancelTitle = "取消"
        var error: NSError?
        
        // deviceOwnerAuthentication 使用生物识别、Apple Watch 或设备密码进行用户身份验证
        // deviceOwnerAuthenticationWithBiometrics 使用生物识别技术进行用户身份验证
        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            // 使用身份验证的原因
            let reason = "通过验证指纹/FaceID登录"
            context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { (success, error) in
                if success {
                    DispatchQueue.main.async {
                        print("登录成功")
                    }
                }
                else {
                    DispatchQueue.main.async {
                        print("登录失败",error?.localizedDescription as Any)
                    }
                }
            }
        }
        else {
            if let laError = error as? LAError {
                switch laError.code {
                case .biometryNotEnrolled:
                    //用户没有注册生物识别身份,提醒跳转到设置
                    let alertController = UIAlertController(title: "FaceID/TouchID不可用", message: "是否前往添加FaceID/TouchID", preferredStyle: .alert)
                    let confirmAction = UIAlertAction(title: "确定", style: .default) { action in
                        guard let url = URL(string: "App-prefs:PASSCODE") else { return }
                        if (UIApplication.shared.canOpenURL(url)) {
                            UIApplication.shared.open(url) { success in
                                print(success)
                            }
                        }
                    }
                    let cancelAction = UIAlertAction(title: "取消", style: .default)
                    alertController.addAction(confirmAction)
                    alertController.addAction(cancelAction)
                    vc.present(alertController, animated: true)
                    
                case .userCancel:
                    //用户点击了身份验证对话框中的取消按钮
                    print("用户取消")
                    
                case .biometryNotAvailable:
                    //生物识别在设备上不可用,提醒跳转到设置
                    let alertController = UIAlertController(title: "FaceID/TouchID不可用", message: "是否前往设置开启权限", preferredStyle: .alert)
                    let confirmAction = UIAlertAction(title: "确定", style: .default) { action in
                        if let url = URL(string: UIApplication.openSettingsURLString) {
                            UIApplication.shared.open(url)
                        }
                    }
                    let cancelAction = UIAlertAction(title: "取消", style: .default)
                    alertController.addAction(confirmAction)
                    alertController.addAction(cancelAction)
                    vc.present(alertController, animated: true)
                    
                /// 根据需要自行修改和补充
                default:
                    break
                }
            }
            //输出错误原因
            print("失败",error?.localizedDescription as Any)
        }
    }
}

方法调用

///vc为当前控制器
FaceIDAuth.startAuth(vc)

错误码说明

错误码说明请参考LAError.Code

官方说明

Local Authentication:通过生物特征或用户已知的密码对用户进行身份验证。

为了最大限度地提高安全性,您的应用永远不会获得对任何底层身份验证数据的访问权限。例如,您无法访问任何指纹图像。Secure Enclave 是一种基于硬件的安全处理器,与系统的其余部分隔离开来,它管理这些数据,即使是操作系统也无法访问。相反,您指定一个特定的策略并提供消息来告诉用户您为什么希望他们进行身份验证。然后,该框架与 Secure Enclave 协调以执行操作。之后,您只会收到一个指示身份验证成功或失败的布尔结果。