しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

iPhone Xの顔認証(FaceID)の実装、iPhoneシミュレータでの検証方法を調べてみる(Swift)

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)
            }
        }
    }
}

【iOS】指紋認証を使ってみる - しめ鯖日記

実装は同じなのですが、顔認証を使う際はInfo.plistにNSFaceIDUsageDescriptionを追加する必要があります。

f:id:llcc:20180704215345p:plain

これを追加しないと下のようなエラーが発生します。

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.

キーをセットすれば下のように権限を求めるポップアップが出るようになります。

f:id:llcc:20180704215355p:plain

顔認証をシミュレータで検証する

顔認証ですがiPhoneシミュレータで検証することもできます。
シミュレータで使うためには、メニューのHardwareのFace IDでEnrolledにチェックを入れる必要があります。

f:id:llcc:20180704215259p:plain

チェックを入れると下のようにシミュレータで顔認証を求める表示が出ます。

f:id:llcc:20180704215550p:plain

顔認証の成功・失敗はシミュレータのメニューのHardwareのFace IDで選択します。

f:id:llcc:20180704215600p:plain

顔認証(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
}