導語
蘋果在iPhone 5s之后添加了Touch ID指紋識別功能,用戶可以通過指紋來對iPhone進行安全而高效的訪問∈趸#現(xiàn)在很多應(yīng)用都添加了指紋識別薪伏,如QQ登錄,支付寶支付等等粗仓。
利用Touch ID進行指紋解鎖
http://upload-images.jianshu.io/upload_images/679533-268db1e09507a065.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
https://github.com/chlsix/TouchIDDemo源代碼地址說明
Touch ID的調(diào)用接口是LocalAuthentication.framework嫁怀,調(diào)用時需要導入頭文件
<pre>#import <LocalAuthentication/LocalAuthentication.h></pre>
2.需要用的方法有兩個
<pre> - (BOOL)canEvaluatePolicy:(LAPolicy)policy
error:(NSError * __autoreleasing *)error attribute((swift_error(none)));</pre>
用來驗證設(shè)備支不支持Touch ID
<pre> - (void)evaluatePolicy:(LAPolicy)policy
localizedReason:(NSString *)localizedReason
reply:(void(^)(BOOL success, NSError * __nullable error))reply;</pre>
驗證Touch ID(會有彈出框)
3.當輸入錯誤的指紋時會彈出"再試一次"驗證框
http://upload-images.jianshu.io/upload_images/679533-4b35d569f20be88e.PNG?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240
<pre> //初始化
LAContext context = [LAContext new];
/* 這個屬性用來設(shè)置指紋錯誤后的彈出框的按鈕文字
- 不設(shè)置默認文字為“輸入密碼”
- 設(shè)置@""將不會顯示指紋錯誤后的彈出框
*/
context.localizedFallbackTitle = @"忘記密碼";</pre>
4.回調(diào)方法
接口提供了Touch ID驗證成功和失敗的回調(diào)方法
<pre>[context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics
localizedReason:@"指紋驗證"
reply:^(BOOL success, NSError * _Nullable error) {
if (success) {
//驗證成功執(zhí)行
NSLog(@"指紋識別成功");
//在主線程刷新view,不然會有卡頓
dispatch_async(dispatch_get_main_queue(), ^{
[view removeFromSuperview];
//保存設(shè)置狀態(tài)
[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d", sender.isOn] forKey:@"touchOn"];
});
} else {
if (error.code == kLAErrorUserFallback) {
//Fallback按鈕被點擊執(zhí)行
NSLog(@"Fallback按鈕被點擊");
} else if (error.code == kLAErrorUserCancel) {
//取消按鈕被點擊執(zhí)行
NSLog(@"取消按鈕被點擊");
} else {
//指紋識別失敗執(zhí)行
NSLog(@"指紋識別失敗");
}
dispatch_async(dispatch_get_main_queue(), ^{
[view removeFromSuperview];
[sender setOn:!sender.isOn animated:YES];
[[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d", sender.isOn] forKey:@"touchOn"];
});
}
}];</pre>