現(xiàn)在為了安全,對于指紋解鎖的應(yīng)用越來越多.蘋果有完善的 API, 只要簡單的調(diào)用就可以實現(xiàn).下面看一下怎么使用.
- 導(dǎo)入需要的框架
#import <LocalAuthentication/LocalAuthentication.h>
2.這里用到了一個新的類LAContext,初始化對象.
LAContext *lac = [[LAContext alloc] init];
// 判斷是否支持指紋解鎖
BOOL isSupport = [lac canEvaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil];
- 處理業(yè)務(wù)邏輯
if (isSupport) {
// localizedReason: 提示語,比如qq的@"通過驗證指紋解鎖 QQ"
[lac evaluatePolicy:kLAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"哈哈" reply:^(BOOL success, NSError * _Nullable error) {
// 當(dāng)前線程是在子線程
NSLog(@"===%@", [NSThread currentThread]);
if (success) {
// 處理解鎖成功的 業(yè)務(wù)邏輯 如果是更新 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)
{
// 授權(quán)失敗
LAErrorAuthenticationFailed = kLAErrorAuthenticationFailed,
// 用戶取消
LAErrorUserCancel = kLAErrorUserCancel,
// 用戶選擇輸入密碼
LAErrorUserFallback = kLAErrorUserFallback,
// 系統(tǒng)取消授權(quán)(例如其他APP切入)
LAErrorSystemCancel = kLAErrorSystemCancel,
// 未設(shè)置密碼
LAErrorPasscodeNotSet = kLAErrorPasscodeNotSet,
// Touch ID不可用,例如未打開
LAErrorTouchIDNotAvailable = kLAErrorTouchIDNotAvailable,
//設(shè)備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(@"系統(tǒng)取消驗證");
break;
case LAErrorUserCancel:
NSLog(@"用戶取消");
break;
case LAErrorUserFallback:
NSLog(@"用戶選擇其他方式");
break;
default:
break;
}
}];
}
目前的效果
QQ 的效果
- 注意事項:
我們會發(fā)現(xiàn)和 QQ 的效果不太一樣. 其實LAContext有一個屬性*localizedFallbackTitle,如果沒有設(shè)置,默認(rèn)就是輸入密碼.
// 這里設(shè)置成空字符串,就會達(dá)到 QQ 那種只有一個選項的效果.
lac.localizedFallbackTitle = @"";