■TouchID認証を使ってみました

TouchID認証を使ってみました

サンプルアプリ

認証ボタンのみを持つアプリとして作成しました。

f:id:unokun3:20170101100939p:plain

起動時

利用可能かどうかチェックします。 LAContext.canEvaluatePolicyを呼び出します。このメソッドは、true/falseを返します。falseの場合、error.localizedDescriptionに説明が入っています。

第1引数をdeviceOwnerAuthenticationWithBiometricsとするとTouch ID認証ができない端末ではエラーになるので、deviceOwnerAuthenticationを使うのが一般的でしょうか?

LAPolicy 説明
deviceOwnerAuthenticationWithBiometrics Touch IDを使った端末のオーナー認証
deviceOwnerAuthentication Touch IDを使った、あるいはパスコードによる端末のオーナー認証
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let context = LAContext()
        var error: NSError?
        let result = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
        if !result {
            authButton.isEnabled = false
            var message = ""
            if let detail = error {
                message = detail.localizedDescription
//                print("error => \(detail.localizedDescription)")
            }
            let alertController: UIAlertController = UIAlertController(title: "アラート表示", message: message, preferredStyle:  UIAlertControllerStyle.alert)
            let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{
                // ボタンが押された時の処理を書く(クロージャ実装)
                (action: UIAlertAction!) -> Void in
                print("OK")
            })
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
            
        }
    }

認証ボタンタップ時

認証します。 LAContext.evaluatePolicyメソッドを呼び出します。 f:id:unokun3:20170101101005p:plain

    @IBAction func tapAuthButton(_ sender: UIButton) {
        let context = LAContext()
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "アプリの認証に使う") { success, error in
            if success {
                print("available")
                return
            }
            var message = ""
            if let detail = error {
                message = detail.localizedDescription
                
            }
            let alertController: UIAlertController = UIAlertController(title: "認証", message: message, preferredStyle:  UIAlertControllerStyle.alert)
            // OKボタン
            let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:{
                // ボタンが押された時の処理を書く(クロージャ実装)
                (action: UIAlertAction!) -> Void in
                print("OK")
            })
            alertController.addAction(defaultAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }

キャンセルが選択された場合は、error.localizedDescriptionにCanceled by userというメッセージが格納されます。

f:id:unokun3:20170101101020p:plain

参考