說明
iPhone X 以後支持Face ID, iPhone 5S以後支持Touch ID. 怎麼準確判斷機器是否支持,Face ID或者Touch ID呢? 實際上系統有方法判斷,但是如果沒有註冊Face ID或者Touch ID,判斷結果也是none
解決方法
用swift 5來解決
import Foundation
import LocalAuthentication
extension LAContext {
enum BiometricType: String {
case none
case touchID
case faceID
}
var biometricType: BiometricType {
var error: NSError?
guard self.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
// Capture these recoverable error through fabric
return .none
}
if #available(iOS 11.0, *) {
switch self.biometryType {
case .touchID:
return .touchID
case .faceID:
return .faceID
default:
return .none
}
}
return self.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) ? .touchID : .none
}
}
調用方法
// need to import LocalAuthentication in the calling file
// import LocalAuthentication
let currentType = LAContext().biometricType
print("biometry type > \(currentType)")
// biometry type > touchID
如果用模擬器來調試,需要開啓Touch ID或者Face ID已經註冊。設置路徑如下
Simulator > Hardware > Touch ID/Face ID > Enrolled.
參考
https://stackoverflow.com/questions/46887547/how-to-programmatically-check-support-of-face-id-and-touch-id/62299672#62299672