swift iOS,仅对应用程序功能的子集使用生物识别身份验证

qyzbxkaa  于 2023-05-05  发布在  Swift
关注(0)|答案(3)|浏览(268)

我正在开发一个应用程序,用户只需要对某些功能进行身份验证,但他们应该对其余功能保持“匿名”。当用户尝试访问特定功能时,是否有方法在应用程序中实现生物识别身份验证?
例如,要参与应用程序中的开放论坛,他们不需要进行身份验证,但一旦他们尝试发送直接消息,他们就需要使用Touch ID或Face ID进行身份验证。这可以做到吗,还是只能在用户打开应用时使用生物识别认证?

ki1q1bka

ki1q1bka1#

是的,你可以在任何你想用的地方使用它。只需请求进行身份验证,然后在身份验证成功完成后,显示另一个ViewController。

vlju58qv

vlju58qv2#

你可以在任何你想要的地方进行生物识别认证,这里有一个你可以尝试的示例:

func authenticationWithTouchID(completion: (Bool) -> ()) {
    let localAuthenticationContext = LAContext()
    localAuthenticationContext.localizedFallbackTitle = "Use Passcode"

    var authError: NSError?
    let reasonString = "To access the secure data"

    if localAuthenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {

        localAuthenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString) { success, evaluateError in
            if success {
                completion(true)
            } else {
                //TODO: User did not authenticate successfully, look at the error and take appropriate action
                guard let error = evaluateError else { return }
                print(self.evaluateAuthenticationPolicyMessageForLA(errorCode: error._code))
                //TODO: If you have choosen the 'Fallback authentication mechanism selected' (LAError.userFallback). Handle gracefully
                completion(false)
            }
        }
    } else {
        guard let error = authError else { return }
        //TODO: Show appropriate alert if biometry/TouchID/FaceID is lockout or not enrolled
        print(self.evaluateAuthenticationPolicyMessageForLA(errorCode: error.code))
    }
}

func evaluatePolicyFailErrorMessageForLA(errorCode: Int) -> String {
    var message = ""
    if #available(iOS 11.0, macOS 10.13, *) {
        switch errorCode {
            case LAError.biometryNotAvailable.rawValue:
                message = "Authentication could not start because the device does not support biometric authentication."

            case LAError.biometryLockout.rawValue:
                message = "Authentication could not continue because the user has been locked out of biometric authentication, due to failing authentication too many times."

            case LAError.biometryNotEnrolled.rawValue:
                message = "Authentication could not start because the user has not enrolled in biometric authentication."

            default:
                message = "Did not find error code on LAError object"
        }
    } else {
        switch errorCode {
            case LAError.touchIDLockout.rawValue:
                message = "Too many failed attempts."

            case LAError.touchIDNotAvailable.rawValue:
                message = "TouchID is not available on the device"

            case LAError.touchIDNotEnrolled.rawValue:
                message = "TouchID is not enrolled on the device"

            default:
                message = "Did not find error code on LAError object"
        }
    }
    return message;
}

func evaluateAuthenticationPolicyMessageForLA(errorCode: Int) -> String {
    var message = ""
    switch errorCode {

    case LAError.authenticationFailed.rawValue:
        message = "The user failed to provide valid credentials"

    case LAError.appCancel.rawValue:
        message = "Authentication was cancelled by application"

    case LAError.invalidContext.rawValue:
        message = "The context is invalid"

    case LAError.notInteractive.rawValue:
        message = "Not interactive"

    case LAError.passcodeNotSet.rawValue:
        message = "Passcode is not set on the device"

    case LAError.systemCancel.rawValue:
        message = "Authentication was cancelled by the system"

    case LAError.userCancel.rawValue:
        message = "The user did cancel"

    case LAError.userFallback.rawValue:
        message = "The user chose to use the fallback"

    default:
        message = evaluatePolicyFailErrorMessageForLA(errorCode: errorCode)
    }
    return message
}

现在你可以在任何地方使用这个功能

authenticationWithTouchID(completion: {(success) in
    if success {
         //TODO: User authenticated successfully, take appropriate action     
    } else {
         //TODO: User authenticateion failed, take appropriate action
    }
})
i34xakig

i34xakig3#

import Foundation
import LocalAuthentication

enum AuthenticationError {
  case BiometricLockOut
  case AppCancel
  case AuthenticatonFailed
  case BiometryNotEnrolled
  case BiometryNotAvailable
  case PasscodeNotSet
  case SystemError
  case UserFallback
  case UserCancel
  case Unknown
}

class LocalAuthentication {

typealias completionHandler = (_ success: Bool, _ error: AuthenticationError?)->()

private static let authenticationString = "App wants to Authenticate User"
private static let context = LAContext()

static func authenticate(authenticationPromptText: String = authenticationString, handler: @escaping completionHandler) {
    
    var error: NSError?
    
    // Ask for Authentication
    if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
        
        context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: authenticationPromptText, reply: { (success, error) in
            
            guard error == nil else {
                
                //onFailure
                let errorType = predictError(error: error as! NSError)
                handler(false, errorType)
                return
            }
            
            //onSuccess Authentication
            handler(true, nil)
        })
    }
}

static func predictError(error: NSError) -> AuthenticationError  {
    
    if #available(iOS 11.0, *) {
        
        switch error.code {
            
        case LAError.authenticationFailed.rawValue:
            return AuthenticationError.AuthenticatonFailed
            
        case LAError.biometryNotEnrolled.rawValue:
            return AuthenticationError.BiometryNotEnrolled
            
        case LAError.userCancel.rawValue:
            return AuthenticationError.UserCancel
            
        case LAError.appCancel.rawValue:
            return AuthenticationError.AppCancel
            
        case LAError.biometryLockout.rawValue:
            return AuthenticationError.BiometricLockOut
            
        case LAError.biometryNotAvailable.rawValue:
            return AuthenticationError.BiometryNotAvailable
            
        case LAError.passcodeNotSet.rawValue:
            return AuthenticationError.PasscodeNotSet
            
        case LAError.systemCancel.rawValue:
            return AuthenticationError.SystemError
            
        case LAError.userFallback.rawValue:
            return AuthenticationError.UserFallback
            
        default:
            return AuthenticationError.Unknown
        }
    } else {
        // Fallback on earlier versions
    }
    
    return AuthenticationError.Unknown
}

}

需要拨打如下电话:

LocalAuthentication.authenticate { (hasAuthenticated, error) in

        if hasAuthenticated {
            print("Success")
        }
        else {
            print(error)
        }
  }

相关问题