Touch ID 指紋識別首次應(yīng)用是在2013年9月發(fā)布的iPhone 5s 上仑濒。在今天,指紋識別已經(jīng)是所有智能手機(jī)必不可少的一部分。它不僅能保證手機(jī)中信息的安全拐云,管理自己的隱私婿着,還能夠快捷快速的進(jìn)行密碼輸入等操作授瘦。在保證安全的同時也提高了使用的效率。
雖說Touch ID 誕生在iPhone 5s竟宋,但是在iOS 8 中才正式開放API提完。而且隨著手機(jī)硬件的升級,Touch ID 的識別效率大大提高丘侠,這使得越來越多的App加入了指紋解鎖的功能徒欣。
LAContext
提供了關(guān)于指紋識別的接口。這里有幾個主要的方法和屬性:
canEvaluatePolicy
方法來判斷設(shè)備是否支持指紋識別蜗字。
evaluatePolicy
方法來進(jìn)行指紋識別打肝。
invalidate
方法主動讓指紋識別上下文失效官研。 (iOS 9+)
localizedFallbackTitle
屬性 設(shè)置驗(yàn)證第一次失敗后顯示按鈕的標(biāo)題。
localizedCancelTitle
屬性設(shè)置取消驗(yàn)證按鈕的標(biāo)題闯睹。
使用
在iOS 中加入Touch ID 指紋非常簡單戏羽,只需要幾句代碼就能搞定,
首先需要引入LocalAuthentication
import LocalAuthentication
初始化驗(yàn)證上下文
let context = LAContext()
// 在第一次驗(yàn)證失敗之后楼吃,可以提供別的方式的入口
context.localizedFallbackTitle = "使用密碼登錄"
進(jìn)行驗(yàn)證始花,蘋果提供了一個LAError 來捕捉Touch ID 驗(yàn)證過程中可能會出現(xiàn)的錯誤,我們可以針對錯誤類型來進(jìn)行預(yù)期處理孩锡。
var contentError: NSError?
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &contentError) {
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "按下你的手指", reply: { (success, error) in
if success {
print("驗(yàn)證成功")
} else {
if let error = error as? LAError {
switch error.code {
/// Authentication was not successful, because user failed to provide valid credentials.
case .authenticationFailed:
print("連續(xù)3次驗(yàn)證失敗")
/// Authentication was canceled by user (e.g. tapped Cancel button).
case .userCancel:
print("用戶取消驗(yàn)證")
/// Authentication was canceled, because the user tapped the fallback button (Enter Password).
case .userFallback:
OperationQueue.main.addOperation {
print("用戶選擇輸入密碼酷宵,切換主線程處理")
}
/// Authentication was canceled by system (e.g. another application went to foreground).
case .systemCancel:
print("系統(tǒng)取消")
/// Authentication could not start, because passcode is not set on the device.
case .passcodeNotSet:
print("未設(shè)置密碼")
/// Authentication could not start, because Touch ID is not available on the device.
case .touchIDNotAvailable:
print("硬件問題導(dǎo)致不可用")
/// Authentication could not start, because Touch ID has no enrolled fingers.
case .touchIDNotEnrolled:
print("手指未登記")
/// Authentication was not successful, because there were too many failed Touch ID attempts and
/// Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating
/// LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
/// iOS 9+
case .touchIDLockout:
print("TouchID鎖定")
/// Authentication was canceled by application (e.g. invalidate was called while
/// authentication was in progress).
/// iOS 9+
case .appCancel:
print("程序退出")
/// LAContext passed to this call has been previously invalidated.
/// iOS 9+
case .invalidContext:
print("無效的驗(yàn)證上下文")
}
}
}
})
}