如何在iOS 10中使用TouchID

9

我想在我的iOS应用程序中实现本地认证安全,但我遇到了错误,并且无法弄清楚为什么会出现这个问题。

我正在使用iPhone 5s,这是否有影响?

代码:

import UIKit
import LocalAuthentication

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func action(_ sender: Any) {
        authenticateUser()
    }

    func authenticateUser() {
        let authContext : LAContext = LAContext()
        var error: NSError?

        if authContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error){
            authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Check for application", reply: {(successful: Bool, error: NSError?) -> Void in
                if successful{
                    print("TouchID Yes")
                }
                else{
                    print("TouchID No")
                }
                } as! (Bool, Error?) -> Void)
        }
        else{
            authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: "Enter your Passcode", reply: {
                (successful: Bool, error: NSError?) in
                if successful{
                    print("PassCode Yes")
                }
                else{
                    print("PassCode No")
                }
                } as! (Bool, Error?) -> Void)
        }
    }
}
错误:

输入图像描述

提前感谢。

1个回答

5

这段代码在没有类型转换的情况下应该可以工作。

func authenticateUser() {
    let authContext : LAContext = LAContext()
    var error: NSError?

    if authContext.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error){
        authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Biometric Check for application", reply: {successful, error -> Void in
            if successful{
                print("TouchID Yes")
            }
            else{
                print("TouchID No")
            }
        }
        )
    }
    else{
        authContext.evaluatePolicy(LAPolicy.deviceOwnerAuthentication, localizedReason: "Enter your Passcode", reply: {
            successful,error in
            if successful{
                print("PassCode Yes")
            }
            else{
                print("PassCode No")
            }
        }
        )
    }
}

请解释为什么这样修复问题:因为你不能对闭包进行类型转换,因为那是没有意义的。 - Bruno Philipe
这不是将NSError强制转换为Error,因为这不是你使用强制转换所做的事情。闭包是一种类型,对不相关类型进行强制转换将始终失败。12 as! String会抛出异常。同样地,当你将((Bool, NSError?) -> Void)强制转换为不相关类型((Bool,Error?) -> Void)时,也会得到一个异常。仅仅因为NSError和Error是相关的,并不意味着具有不同签名的闭包是相关的。 - Paulw11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接