现在为了安全,对于指纹解锁的应用越来越多.苹果有完善的 API, 只要简单的调用就可以实现.下面看一下怎么使用.
- 导入需要的框架
#import <LocalAuthentication/LocalAuthentication.h>
2.这里用到了一个新的类LAContext,初始化对象.
LAContext *lac = [[LAContext alloc] init];
// 判断是否支持指纹解锁
BOOL isSupport = [lac canEvaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil];
- 处理业务逻辑
if (isSupport) {
// localizedReason: 提示语,比如qq的@"通过验证指纹解锁 QQ"
[lac evaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"哈哈" reply:^(BOOL success, NSError * _Nullable error) {
// 当前线程是在子线程
NSLog(@"===%@", [NSThread currentThread]);
if (success) {
// 处理解锁成功的 业务逻辑 如果是更新 UI 一定要放在主线程中
NSLog(@"指纹解锁成功");
dispatch_async(dispatch_get_main_queue(), ^{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor redColor];
[self.window addSubview:view];
});
/*
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor redColor];
[self.window addSubview:view];
// This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release.
*/
} else {
/*
typedef NS_ENUM(NSInteger, LAError)
{
// 授权失败
LAErrorAuthenticationFailed = kLAErrorAuthenticationFailed,
// 用户取消
LAErrorUserCancel = kLAErrorUserCancel,
// 用户选择输入密码
LAErrorUserFallback = kLAErrorUserFallback,
// 系统取消授权(例如其他APP切入)
LAErrorSystemCancel = kLAErrorSystemCancel,
// 未设置密码
LAErrorPasscodeNotSet = kLAErrorPasscodeNotSet,
// Touch ID不可用,例如未打开
LAErrorTouchIDNotAvailable = kLAErrorTouchIDNotAvailable,
//设备Touch ID不可用,用户未录入
LAErrorTouchIDNotEnrolled = kLAErrorTouchIDNotEnrolled,
// 后面三种情况是9.0之后新增的.
// 多次错误需要输入密码
LAErrorTouchIDLockout NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorTouchIDLockout,
// app 取消验证
LAErrorAppCancel NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorAppCancel,
// context 被释放了
LAErrorInvalidContext NS_ENUM_AVAILABLE(10_11, 9_0) = kLAErrorInvalidContext
} NS_ENUM_AVAILABLE(10_10, 8_0);
*/
NSLog(@"---%@", error.localizedDescription);
switch (error.code) {
case LAErrorSystemCancel:
NSLog(@"系统取消验证");
break;
case LAErrorUserCancel:
NSLog(@"用户取消");
break;
case LAErrorUserFallback:
NSLog(@"用户选择其他方式");
break;
default:
break;
}
}];
}
- 注意事项:
我们会发现和 QQ 的效果不太一样. 其实LAContext有一个属性*localizedFallbackTitle,如果没有设置,默认就是输入密码.
// 这里设置成空字符串,就会达到 QQ 那种只有一个选项的效果.
lac.localizedFallbackTitle = @"";