如何在用户拒绝授权后检测设备是否支持Touch ID/Face ID?
检测iOS设备原生支持Touch ID还是Face ID(不受用户授权状态影响)
你遇到的问题很典型——当用户拒绝授权生物识别后,LAContext的biometryType会返回LABiometryTypeNone,导致无法判断设备硬件本身支持的是Touch ID还是Face ID。下面是一个可靠的解决方案,不管用户是否授权,都能准确识别设备原生支持的生物识别类型:
核心思路
- 当
canEvaluatePolicy返回YES时,直接通过context.biometryType获取类型即可 - 当
canEvaluatePolicy返回NO时,通过错误信息判断:- 如果错误码是
LAErrorBiometryDenied(用户拒绝授权)、LAErrorBiometryLockout(生物识别锁定)或LAErrorBiometryNotEnrolled(未录入生物识别),说明设备硬件本身支持生物识别,此时在iOS 11+可以从错误的userInfo中提取LAErrorBiometryTypeKey来获取原生支持的类型 - 如果错误码是
LAErrorBiometryNotAvailable,说明设备不支持任何生物识别
- 如果错误码是
完整代码示例
#import <LocalAuthentication/LocalAuthentication.h> - (void)detectDeviceBiometryType { LAContext *context = [[LAContext alloc] init]; NSError *error = nil; BOOL canEvaluate = [context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]; if (canEvaluate) { // 设备支持生物识别且用户已授权 if (@available(iOS 11.0, *)) { if (context.biometryType == LABiometryTypeFaceID) { NSLog(@"设备原生支持Face ID"); } else if (context.biometryType == LABiometryTypeTouchID) { NSLog(@"设备原生支持Touch ID"); } } else { // iOS 11以下系统仅支持Touch ID NSLog(@"设备原生支持Touch ID"); } } else { // 无法评估策略,检查错误原因 switch (error.code) { case LAErrorBiometryDenied: case LAErrorBiometryLockout: case LAErrorBiometryNotEnrolled: { // 设备硬件支持生物识别,但存在授权/录入/锁定问题 if (@available(iOS 11.0, *)) { NSNumber *biometryTypeNum = error.userInfo[LAErrorBiometryTypeKey]; LABiometryType type = (LABiometryType)[biometryTypeNum integerValue]; if (type == LABiometryTypeFaceID) { NSLog(@"设备原生支持Face ID(用户已拒绝授权)"); } else if (type == LABiometryTypeTouchID) { NSLog(@"设备原生支持Touch ID(用户已拒绝授权/未录入)"); } } else { // iOS 11以下系统仅支持Touch ID NSLog(@"设备原生支持Touch ID(用户已拒绝授权/未录入)"); } break; } case LAErrorBiometryNotAvailable: NSLog(@"设备不支持任何生物识别"); break; default: NSLog(@"其他错误:%@", error.localizedDescription); break; } } }
关键细节
LAErrorBiometryTypeKey是iOS 11新增的键,专门用于在生物识别授权失败时返回设备原生支持的生物识别类型- iOS 11及以下系统没有Face ID,所以可以直接判定为Touch ID
- 这个方法完全不依赖用户的授权状态,只检测设备硬件层面的支持类型,完美匹配你的需求
内容的提问来源于stack exchange,提问作者Furkan yeşiloğlu
相关产品推荐
相关产品推荐

