项目设置
- 权限声明:
在
Info.plist
文件中添加权限相关的键值对。
- 对于 Touch ID,添加
NSFaceIDUsageDescription
键,类型为 String
,描述用户使用 Touch ID 进行身份验证的原因,例如 “Your biometric data will be used by the app for authentication purposes only.”。虽然键名为 NSFaceIDUsageDescription
,但它同时适用于 Touch ID 和 Face ID。
代码配置
- 导入框架:
在需要使用 Touch ID 或 Face ID 的文件中导入
LocalAuthentication
框架。
#import <LocalAuthentication/LocalAuthentication.h>
- 检查设备支持及配置:
在视图控制器或相关逻辑类中编写代码检查设备是否支持生物识别认证并进行相应配置。
- (void)authenticateUser {
LAContext *context = [[LAContext alloc] init];
NSError *error = nil;
if (![context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
// 设备不支持生物识别认证
if (error) {
NSLog(@"Error: %@", error);
}
// 可以选择提供其他的认证方式,如密码
return;
}
NSString *reason = @"Use biometric authentication to access your account";
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) {
if (success) {
// 生物识别认证成功,执行相应逻辑
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Biometric authentication succeeded.");
// 例如跳转到主界面等
});
} else {
if (error) {
NSLog(@"Biometric authentication failed: %@", error);
}
// 认证失败处理,如提示用户重试或选择其他认证方式
}
}];
}