1. 程式人生 > >Swift TouchId 實現指紋登入

Swift TouchId 實現指紋登入

import Foundation
import LocalAuthentication

class TouchIdManager: NSObject {
    
    @objc enum TouchIdResult: NSInteger {
        case success
        case failed
        case passwordNotSet
        case touchidNotSet
        case touchidNotAvailable
        case systemCancle
        case userCancel
        case inputPassword
    }
    
    static var hasTouchId: Bool {
        if #available(iOS 8.0, OSX 10.12, *) {
            let context = LAContext()
            var error: NSError? = nil
            if(context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error)) {
                return true
            }
        }
        return false
    }
    
    static func startFingerUnlock(withtips tips:String, block : @escaping (_ result :TouchIdResult) -> Void) {
        if #available(iOS 8.0, OSX 10.12, *) {
            let context = LAContext()
            var error: NSError? = nil
            if(context.canEvaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, error: &error)) {
                context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason:tips, reply: { (success, error) in
                    if(success) {
                        block(.success)
                    } else {
                        let laerror = error as! LAError
                        switch laerror.code {
                        case LAError.authenticationFailed:
                            block(.failed)
                            break
                        case LAError.userCancel:
                            block(.userCancel)
                            break
                        case LAError.userFallback:
                            block(.inputPassword)
                            break
                        case LAError.systemCancel:
                            block(.systemCancle)
                            break
                        case LAError.passcodeNotSet:
                            block(.passwordNotSet)
                            break
                        case LAError.touchIDNotAvailable:
                            block(.touchidNotAvailable)
                            break
                        case LAError.touchIDNotEnrolled:
                            block(.touchidNotSet)
                            break
                        default: break
                        }
                    }
                })
            } else {
                block(.touchidNotAvailable)
            }
        }
    }
    
}