您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 指紋識別(Touch ID)集成完全指南

編輯:iOS 技巧大全

在講求安全與效率兼得的今天,普通密碼已無法滿足需求,指紋識別應運而生。每個人都有專屬的指紋,在支付等需要驗證的场景,只需輕輕一按即可完成,既安全又便捷,還免去了忘記密碼的煩惱。

聽起來很高大上,但實現起來其實非常簡單,因為蘋果已經幫我們封裝好了,只需簡單調用即可。

步驟一:導入頭文件

#import <LocalAuthentication/LocalAuthentication.h>

步驟二:判斷設備支持並發起驗證

先判斷設備是否支持指紋識別(需 iPhone5s 及以上、iOS8.0 及以上),再判斷當前用戶是否是機主即可。

 - (IBAction)biologyAction:(id)sender { LAContext *context = [[LAContext alloc] init]; NSError *error = nil; NSString *reason = @"我們需要驗證您的指紋來確認您的身份"; // 判斷設備是否支持指紋識別 if([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]){ // 指紋識別只判斷當前用戶是否是機主 [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) { if(success){ NSLog(@"指紋認證成功"); } else{ NSLog(@"指紋認證失敗"); NSLog(@"錯誤碼:%zd",error.code); // -1: 連續三次指紋識別錯誤 // -2: 在TouchID對話框中點擊了取消按鈕 // -3: 在TouchID對話框中點擊了輸入密碼按鈕 // -4: TouchID對話框被系統取消,例如按下Home或者電源鍵 // -8: 連續五次指紋識別錯誤,TouchID功能被鎖定 } }]; } else{ NSLog(@"TouchID設備不可用"); NSLog(@"錯誤碼:%zd",error.code); } }

Swift 3.0 版本

原理與上面完全相同,只是把 OC 代碼翻譯成了 Swift 3.0:

 import UIKit import LocalAuthentication class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBAction func yanzhengAction(_ sender: AnyObject) { let context = LAContext() let reason = "我們需要您的指紋來驗證您的身份" var error:NSError? if context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error:&error){ context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply: { (isSuc, error) in if isSuc{ print("指紋驗證成功") } else{ print("指紋驗證失敗") print("錯誤信息:\(error)") } }) } else{ print("TouchID設置不支持") print("錯誤信息:\(error)") } } }

透過 LAContext 的 canEvaluatePolicy 判斷支持情況,再調用 evaluatePolicy 發起驗證,就能輕鬆為 App 加入指紋識別能力。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved