簡介
iPhone 5s~iPhone 8都可以通過指紋進行解鎖鸯旁,省去了反復(fù)輸入密碼的繁瑣程序,這個就是Touch ID指紋識別技術(shù)。在iOS 8以后泣港,Apple也開放了Touch ID的API給開發(fā)者,因此很多App也引入了這個新的登錄方式价匠。Face ID實現(xiàn)過程與Touch ID基本相同当纱,后期也會再做補充
開發(fā)應(yīng)用
- 要實現(xiàn)指紋識別的功能需要引入LocalAuthentication框架
- 首先我們需要判斷目前設(shè)備是否支持Touch ID功能
func canEvaluatePolicy(_ policy: LAPolicy, error: NSErrorPointer) -> Bool
- LAPolicy有兩個值,分別是
deviceOwnerAuthenticationWithBiometrics
和deviceOwnerAuthentication
- deviceOwnerAuthenticationWithBiometrics:用手指指紋去驗證,iOS8.0以上可用
- deviceOwnerAuthentication:使用TouchID或者密碼驗證,默認(rèn)是錯誤三次指紋或者鎖定后,彈出輸入密碼界面iOS 9.0以上可用
- 開始指紋驗證
func evaluatePolicy(_ policy: LAPolicy, localizedReason: String, reply: @escaping (Bool, Error?) -> Void)
主要代碼
func evaluate(reason: String, completed: @escaping (_ isSuccess: Bool)->()) {
//記錄是否開啟Touch ID
var canTouchID = true
canTouchID = content.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
guard canTouchID else {
completed(false)
return
}
//本地認(rèn)證上下文聯(lián)系對象踩窖,每次使用Touch ID功能都要重新初始化
content = nil
content = LAContext()
guard let content = content else { return }
//調(diào)起Touch ID驗證彈框
content.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: “指紋驗證登錄”) {
(success, error) in
//成功與失敗進行相應(yīng)的操作
if success {
completed(true)
}else {
completed(false)
print("\(error!)")
if let errorCode = LAError.Code(rawValue: (error! as NSError).code) {
switch errorCode
//對應(yīng)errorCode的相應(yīng)操作
……
}
}
}
}
localizedReason:用于設(shè)置提示語坡氯,表示為什么要使用Touch ID
常見erro描述
- 在模擬器上運行結(jié)果
Error Domain=com.apple.LocalAuthentication Code=-1000 "Simulator is not supported."
UserInfo=0x7ffe604b0790 {NSLocalizedDescription=Simulator is not supported.
- 在有TouchID 的功能下,沒有設(shè)置TouchID的運行結(jié)果
Error Domain=com.apple.LocalAuthentication Code=-7 "No fingers are enrolled with Touch ID."
UserInfo=0x170075fc0 {NSLocalizedDescription=No fingers are enrolled with Touch ID.
- 連續(xù)三次指紋識別錯誤
Error Domain=com.apple.LocalAuthentication Code=-1 "Aplication retry limit exceeded."
UserInfo=0x1740797c0 {NSLocalizedDescription=Aplication retry limit exceeded.}
- 用戶在Touch ID對話框中點擊了取消按鈕
Error Domain=com.apple.LocalAuthentication Code=-2 "Canceled by user."
UserInfo=0x17006c780 {NSLocalizedDescription=Canceled by user.
- Touch ID三次校驗失敗
Error Domain=com.apple.LocalAuthentication Code=-1 "Application retry limit exceeded."
UserInfo={NSLocalizedDescription=Application retry limit exceeded.}
- Touch ID多次校驗失敗
Error Domain=com.apple.LocalAuthentication Code=-8 "Biometry is locked out."
UserInfo={NSLocalizedDescription=Biometry is locked out.
參考文章
http://www.reibang.com/p/aef5a506311b
https://juejin.im/entry/59795ee95188253e000a74c3