集成方法
1). 首先引入指纹解锁必须的头文件
#import <LocalAuthentication/LocalAuthentication.h>
2). 创建LAContext
对象
主要的属性设置
localizedFallbackTitle:用于设置左边的按钮的名称,默认是Enter Password.
localizedReason:用于设置提示语,表示为什么要使用Touch ID
LAContext *context = [LAContext new];
context.localizedFallbackTitle = @"没有忘记密码";
回调方法
NSError *error = nil;
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
NSLog(@"支持指纹识别");
[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"指纹解锁" reply:^(BOOL success, NSError * _Nullable error) {
if (success) {
NSLog(@"验证成功 刷新主界面");
}else{
NSLog(@"%@",error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel:
{
NSLog(@"系统取消授权,如其他APP切入");
break;
}
case LAErrorUserCancel:
{
NSLog(@"用户取消验证Touch ID");
break;
}
case LAErrorAuthenticationFailed:
{
NSLog(@"授权失败");
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"系统未设置密码");
break;
}
case LAErrorTouchIDNotAvailable:
{
NSLog(@"设备Touch ID不可用,例如未打开");
break;
}
case LAErrorTouchIDNotEnrolled:
{
NSLog(@"设备Touch ID不可用,用户未录入");
break;
}
case LAErrorUserFallback:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"用户选择输入密码,切换主线程处理");
}];
break;
}
default:
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"其他情况,切换主线程处理");
}];
break;
}
}
}
}];
}else{
NSLog(@"不支持指纹识别");
switch (error.code) {
case LAErrorTouchIDNotEnrolled:
{
NSLog(@"TouchID is not enrolled");
break;
}
case LAErrorPasscodeNotSet:
{
NSLog(@"A passcode has not been set");
break;
}
default:
{
NSLog(@"TouchID not available");
break;
}
}
NSLog(@"%@",error.localizedDescription);
}
补充:
iOS 9加入了三种新的错误类型。
/// Authentication was not successful, because there were too many failed Touch ID attempts and
/// Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating
/// LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
LAErrorTouchIDLockout NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorTouchIDLockout,
/// Authentication was canceled by application (e.g. invalidate was called while
/// authentication was in progress).
LAErrorAppCancel NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorAppCancel,
/// LAContext passed to this call has been previously invalidated.
LAErrorInvalidContext NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorInvalidContext
其中,LAErrorTouchIDLockout是在8.0中也会出现的情况,但并未归为单独的错误类型,这个错误出现,源自用户多次连续使用Touch ID失败,Touch ID被锁,需要用户输入密码解锁,这个错误的交互LocalAuthentication.framework已经封装好了,不需要开发者关心。
LAErrorAppCancel和LAErrorSystemCancel相似,都是当前软件被挂起取消了授权,但是前者是用户不能控制的挂起,例如突然来了电话,电话应用进入前台,APP被挂起。后者是用户自己切到了别的应用,例如按home键挂起。
LAErrorInvalidContext很好理解,就是授权过程中,LAContext对象被释放掉了,造成的授权失败。
参考出处: http://hiis.me/2016/08/30/iOS开发实现TouchID指纹解锁/
https://segmentfault.com/a/1190000002516465