swift Face ID评估过程无法正常工作

3df52oht  于 2个月前  发布在  Swift
关注(0)|答案(3)|浏览(15)

我正在尝试获取Face ID或Touch ID是否成功执行以下功能

func authenticate() -> Bool{

    let context = LAContext()
    var error: NSError?

    guard context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) else {
        return false
    }
    var returnValue = false
    let reason = "Face ID authentication"
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) 
    {
        isAuthorized, error in
        guard isAuthorized == true else {
            return print(error)
        }
        returnValue = true
        print("success")
    }
    return returnValue        
}

字符串
但是即使它成功地使用了这段代码,它也跳过了returnValue = true,这导致了一个错误的返回。为什么会发生这种情况?我如何修复这段代码,使它像预期的那样工作?
上面的代码来自this link,以防这个人正在观看,谢谢。

t9aqgxwy

t9aqgxwy1#

Touch ID和Face ID LocalAuthentication的工作代码

(swift 4.0和5.0+代码)

注:隐私- Face ID使用说明在Info.plist中添加键

使用

self.Authenticate { (success) in
     print(success)
}

字符串
本地认证功能

import LocalAuthentication

func Authenticate(completion: @escaping ((Bool) -> ())){
    
    //Create a context
    let authenticationContext = LAContext()
    var error:NSError?
    
    //Check if device have Biometric sensor
    let isValidSensor : Bool = authenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
    
    if isValidSensor {
        //Device have BiometricSensor
        //It Supports TouchID
        
        authenticationContext.evaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics,
            localizedReason: "Touch / Face ID authentication",
            reply: { [unowned self] (success, error) -> Void in
                
                if(success) {
                    // Touch / Face ID recognized success here
                    completion(true)
                } else {
                    //If not recognized then
                    if let error = error {
                        let strMessage = self.errorMessage(errorCode: error._code)
                        if strMessage != ""{
                            self.showAlertWithTitle(title: "Error", message: strMessage)
                        }
                    }
                    completion(false)
                }
        })
    } else {
        
        let strMessage = self.errorMessage(errorCode: (error?._code)!)
        if strMessage != ""{
            self.showAlertWithTitle(title: "Error", message: strMessage)
        }
    }
    
}


使用消息处理错误代码

//MARK: TouchID error
func errorMessage(errorCode:Int) -> String{
    
    var strMessage = ""
    
    switch errorCode {
        
    case LAError.Code.authenticationFailed.rawValue:
        strMessage = "Authentication Failed"
        
    case LAError.Code.userCancel.rawValue:
        strMessage = "User Cancel"
        
    case LAError.Code.systemCancel.rawValue:
        strMessage = "System Cancel"
        
    case LAError.Code.passcodeNotSet.rawValue:
        strMessage = "Please goto the Settings & Turn On Passcode"
        
    case LAError.Code.biometryNotAvailable.rawValue:
        strMessage = "TouchI or FaceID DNot Available"
        
    case LAError.Code.biometryNotEnrolled.rawValue:
        strMessage = "TouchID or FaceID Not Enrolled"
        
    case LAError.Code.biometryLockout.rawValue:
        strMessage = "TouchID or FaceID Lockout Please goto the Settings & Turn On Passcode"
        
    case LAError.Code.appCancel.rawValue:
        strMessage = "App Cancel"
        
    case LAError.Code.invalidContext.rawValue:
        strMessage = "Invalid Context"
        
    default:
        strMessage = ""
        
    }
    return strMessage
}


显示警报消息

//MARK: Show Alert
func showAlertWithTitle( title:String, message:String ) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    let actionOk = UIAlertAction(title: "OK", style: .default, handler: nil)
    alert.addAction(actionOk)
    self.present(alert, animated: true, completion: nil)
}

yvfmudvl

yvfmudvl2#

你应该使用闭包来获得计算结果。注意,canEvaluatePolicy的返回值是Bool,但是evaluatePolicy没有返回值,因为它接受一个闭包。
你可以修改你的方法来包含一个闭包而不是return。

func authenticate(completion: ((Bool) -> ())) {
    ...
    completion(true) // false if it failed.
    ...
}

字符串
在应用程序的其他部分,您之前使用返回值的地方,现在必须使用闭包,如:

class Foo {
   func test() {
       let isEvaluated = self.authenticate() // Old way
       self.authenticate { success in
           // bool will now indicate whether evaluation was done successfully or not.
       }
   }
}

t40tm48m

t40tm48m3#

x1c 0d1x的数据

注意:隐私- Face ID使用说明密钥添加在Info.plist中

func canAuthenticate() -> Bool {
    let context = LAContext()
    var error: NSError?
    
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        return true
    } else {
        // Handle the error, if any
        print("Biometric authentication not available: \(error?.localizedDescription ?? "Unknown error")")
        return false
    }
}

func authenticateUser() {
    let context = LAContext()
    
    context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "Authenticate to access the app") { (success, authenticationError) in
        DispatchQueue.main.async { [self] in
            if success {
                // Biometric authentication succeeded
                print("Authentication successful")

            } else {
                // Biometric authentication failed or was canceled
                if let error = authenticationError as? LAError {
                    switch error.code {
                    case .userCancel:
                        print("Authentication canceled by the user")
                    case .userFallback:
                        print("User chose to enter password instead")
                        // Handle password entry here if needed
                    default:
                        print("Authentication failed: \(error.localizedDescription)")
                    }
                }
            }
        }
    }
}

字符串

用法

override func viewDidLoad() {
    super.viewDidLoad()
    if canAuthenticate() {
        authenticateUser()
    }
}

相关问题