You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iPhone X上LAContext.biometryType返回.none的CoreAuthentication问题

解决iPhone X上LAContext.biometryType返回.none的问题

嘿,我一眼就看出问题出在哪了——你每次都创建了全新的LAContext实例!

你看,你先创建了一个LAContext去调用canEvaluatePolicy:error:,然后又新建了另一个LAContext去读取biometryType。但实际上,biometryType这个属性只有在同一个LAContext实例调用过canEvaluatePolicy之后才会被正确赋值,新实例根本没经过政策评估,自然返回.none。

给你修复后的代码,核心就是复用同一个LAContext:

fileprivate let biometricsType: SecurityBiometrics = {
    let context = LAContext()
    var error: NSError?
    
    // 先通过同一个context评估政策,这一步会初始化biometryType的信息
    let canEvaluate = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
    
    guard canEvaluate else {
        // 这里可以根据error做针对性处理,比如用户禁用了生物识别、设备不支持等
        return .none
    }
    
    if #available(iOS 11.0, *) {
        switch context.biometryType {
        case .faceID:
            return .faceID
        case .touchID:
            return .touchID
        default:
            return .none
        }
    } else {
        // iOS 11及以下只有TouchID,能评估成功就是TouchID
        return .touchID
    }
}()

另外还要注意两个关键细节:

  • 必须在Info.plist中添加权限描述:
    • 针对FaceID,要添加NSFaceIDUsageDescription,描述你为什么需要使用FaceID;
    • 针对TouchID,添加NSBiometricUsageDescription即可。
      不添加的话,不仅生物识别功能会失效,还可能导致崩溃。
  • 记得处理canEvaluatePolicy返回false的情况,通过error参数可以判断具体原因:比如LAError.biometryNotAvailable(设备不支持生物识别)、LAError.biometryLockout(生物识别被锁定)、LAError.biometryNotEnrolled(用户未录入生物识别信息)等。

内容的提问来源于stack exchange,提问作者Kevin Machado

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:36:01