TouchID功能是從iPhone5S時代引入的安全功能,經過這個功能用戶能夠省略衆多輸入密碼的繁瑣步驟,而且得到更好的安全性,下面咱們來一塊兒學習一下如何進行TouchID本地驗證.swift
首先建立好項目,選擇Build Phases。在Link Binary with Libraries中將LocalAuthentication的framework添加進項目
在代碼中import引入的framework。
在viewController中import LocalAuthentication安全
接下來在StoryBoard中建立一個按鈕,而且拉一個IBAction,這裏咱們命名爲check
在這個方法中咱們進行本地驗證的具體步驟閉包
//本地驗證上下文對象 let context = LAContext() //驗證錯誤 var authError : NSError? //在驗證界面顯示的文字 let errorReason = "使用TouchID驗證"
接下來就開始實現指紋驗證的主要功能
若能夠進行指紋驗證框架
if context.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &authError){ //若能夠進行指紋驗證 //經過設備自帶的生物識別裝置(TouchID)進行本地驗證 context.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: errorReason, reply: {(success, error) in //驗證結束的閉包,第一個參數爲結果,第二個參數爲錯誤信息 if success { print("驗證成功") } else{ print("驗證失敗") } }) }
若不能進行指紋驗證學習
//若不能進行指紋驗證,經過alertController提示驗證失敗 else{ let alert = UIAlertAction(title: "沒法驗證", style: UIAlertActionStyle.Default, handler: { _ in self.dismissViewControllerAnimated(true, completion: nil) }) let alertController = UIAlertController(title: "驗證結果", message: nil, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(alert) //顯示alertController self.presentViewController(alertController, animated: true, completion: nil) }
最終效果ui