iPhone Xから顔認証が使えるようになったので、実装方法を調べてみました。
顔認証(FaceID)の実装方法(Swift)
実装自体は指紋認証と全く同じです。
下のようにLAContextのevaluatePolicyで認証を呼び出します。
import UIKit import LocalAuthentication class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "テスト認証") { success, error in print(success) } } } }
実装は同じなのですが、顔認証を使う際はInfo.plistにNSFaceIDUsageDescription
を追加する必要があります。
これを追加しないと下のようなエラーが発生します。
This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSFaceIDUsageDescription key with a string value explaining to the user how the app uses this data.
キーをセットすれば下のように権限を求めるポップアップが出るようになります。
顔認証をシミュレータで検証する
顔認証ですがiPhoneシミュレータで検証することもできます。
シミュレータで使うためには、メニューのHardwareのFace IDでEnrolledにチェックを入れる必要があります。
チェックを入れると下のようにシミュレータで顔認証を求める表示が出ます。
顔認証の成功・失敗はシミュレータのメニューのHardwareのFace IDで選択します。
顔認証(Face ID)対応端末かどうかを判定する
Face IDに対応しているかどうかはLAContextのbiometryTypeを使います。
let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) { if context.biometryType == .faceID { } }
biometryTypeの型はLABiometryTypeというenumで、タッチIDかFaceIDかの判定を行う事ができます。
public enum LABiometryType : Int { /// The device does not support biometry. @available(iOS 11.2, *) case none /// The device does not support biometry. @available(iOS, introduced: 11.0, deprecated: 11.2, renamed: "LABiometryType.none") public static var LABiometryNone: LABiometryType { get } /// The device supports Touch ID. case touchID /// The device supports Face ID. case faceID }