使用TouchID指纹认证
本来以为比较多的东西,突然想做一下,查了下,就那么点东西。
首先判断系统版本,要求的最低版本为iOS8.0;
- (BOOL)checkDeviceSystemVersion {
NSString *systemVersion = [UIDevice currentDevice].systemVersion;
if (systemVersion.floatValue >= 8.0) {
return YES;
} else {
return NO;
} }
然后,导入所需要的库
#import<LocalAuthentication/LocalAuthentication.h>;
之后就是固定写法了:
//初始化对象
LAContext* context = [[LAContext alloc] init];
//错误对象
NSError* error = nil;
//这个是touchID下边显示的一行文字,一般用来说明为什么需要指纹认证
NSString* reason = @"需要进行指纹认证";
//touchID认证失败以后出现 默认为"Enter Password",设定nil的话,这个选项会消失
context.localizedFallbackTitle = @"输入密码";
//默认为“cancel”
context.localizedCancelTitle = @"取消";
//首先使用canEvaluatePolicy 判断设备支持状态
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
//支持指纹验证
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError *error) {
if (success) {
//验证成功,主线程处理UI
NSLog(@"验证成功");
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"验证成功" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"再试一次" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
[self authenticationByFingerprint];
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
}];
[alert addAction:resetAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:^{
}];
}
else
{
NSLog(@"%@",error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel:
{
NSLog(@"Authentication was cancelled by the system");
//切换到其他APP,系统取消验证Touch ID
break;
}
case LAErrorUserCancel:
{
NSLog(@"Authentication was cancelled by the user");
//用户取消验证Touch ID
break;
}
case LAErrorUserFallback:
{
NSLog(@"User selected to enter custom password");
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//用户选择其他验证方式,切换主线程处理
}];
break;
}
default:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
//其他情况,切换主线程处理
}];
break;
}
}
}
}];
}
else
{
//不支持指纹识别,LOG出错误详情
switch (error.code) {
case LAErrorTouchIDNotEnrolled:
{
NSLog(@"TouchID is not enrolled");
//touchID不可用 用户未录入
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"A passcode has not been set");
//系统未设置密码
break;
}
default:
{
NSLog(@"TouchID not available");
//touchID不可用 例如设备不支持
break;
}
}
NSLog(@"%@",error.localizedDescription);
}