如何使用Swift使用TouchID?

时间:2014-06-28 07:24:02

标签: ios objective-c swift ios8

Apple为iOS 8的TouchID实现提供的文档在Objective-C中。

是否有Swift版本?

目标-C:

- (IBAction)touchIDAvailable:(UIButton *)touchIDAvailableButton {
    LAContext *context = [[LAContext alloc] init];
    __block  NSString *msg;
    [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(@"Place your finger on the sensor", nil) reply: ^(BOOL success, NSError *authenticationError) {
         if (success) {
         }
    }
}

夫特:

@IBAction func touchidbutton(sender: AnyObject) {
    authContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: "Place your finger on the sensor"?, reply: ((success : Bool, NSError!) -> Void)?){
        if (success) {
        }
    }
}

7 个答案:

答案 0 :(得分:6)

这是我在Swift中执行这些检查的视图控制器。在研究这个时,我发现Swift中的完成块/闭包语法非常混乱。

请注意,Beta 2中的某些选项已更改,以便您可以更好地控制Touch ID对话框,例如禁用后备选项或取消按钮。

// Imports
import UIKit
import LocalAuthentication

// Class Implementation
class FirstViewController: UIViewController {

// Class Properties
@IBOutlet var statusLabel : UILabel
@IBOutlet var headerString: UILabel
var authError : NSError?
var authContext = LAContext()
var statusText = ""
var alert = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.Alert)


// Class Methods
@IBAction func swiftButtonPress(sender : AnyObject) {

    statusLabel.text = "Authenticating"

    //Can we use local auth?
    if authContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &authError) {

        authContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics,
            localizedReason: "I need to see if it's really you",
            reply: {(success: Bool, error: NSError!) -> Void in

                if success {
                    self.statusText = "Touch ID success!"
                    self.alert.title = "Success"
                    self.alert.message = "I knew it was you!"
                } else {
                    self.statusText = "Touch ID failed!"
                    self.alert.title = "Failure"

                    switch error!.code {
                    case LAError.AuthenticationFailed.toRaw():
                        self.alert.message = "Authentication Failed"
                    case LAError.UserCancel.toRaw():
                        self.alert.message = "User canceled!"
                    case LAError.SystemCancel.toRaw():
                        self.alert.message = "The system canceled!"
                    case LAError.UserFallback.toRaw():
                        self.alert.message = "User request to enter passcode"
                    default:
                        self.alert.message = "Something else went wrong"
                    }
                }
                self.presentViewController(self.alert, animated: true, completion:{self.statusLabel.text = self.statusText})
            })
    } else {
        self.statusText = "No local authentication"
        alert.title = "Uh oh!"

        switch authError!.code {
        case LAError.TouchIDNotAvailable.toRaw():
            alert.message = "No Touch ID on device"
        case LAError.TouchIDNotEnrolled.toRaw():
            alert.message = "No fingers enrolled"
        case LAError.PasscodeNotSet.toRaw():
            alert.message = "No passcode set"
        default:
            alert.message = "Something went wrong getting local auth"
        }
        self.presentViewController(self.alert, animated: true, completion: {self.statusLabel.text = self.statusText})
    }
    resetTouchID()
}

// Reset the system so we can go again
func resetTouchID() {
    authContext = LAContext()
    alert = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil))
    let passcodeDetector = SwiftPasscodeDetector()
    if passcodeDetector.checkForPasscode() {
        headerString.text = "Passcode Set on Device"
    } else {
        headerString.text = "No Passcode Set"
    }

}

// Inherited Methods
override func viewDidLoad() {
    super.viewDidLoad()
    resetTouchID()
}

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

}

答案 1 :(得分:2)

LAContext reference在Obj-C和Swift中都有方法签名。此外,如果您在Swift代码中单击LAContext类,您应该能够在Swift中查看生成的“标题”。

答案 2 :(得分:2)

API名称为LAContext,位于文档right here中。它很稀疏,但它确实起作用。你可能想要的方法是

evaluatePolicy(_ policy: LAPolicy,
    localizedReason localizedReason: String!, 
    reply reply: ((Bool, NSError!) -> Void)!)

字符串参数是要显示给用户的子标题,回复只是一个回调块,策略当前必须是LAPolicy.DeviceOwnerAuthenticationWithBiometrics,但是看起来框架是用于其他类型的身份验证的未来。有意思......

希望有所帮助!我试着打电话,因为我很好奇,而且效果非常好。只需确保在尝试使用之前查询评估策略的能力,以防它出现在较旧的设备上。

答案 3 :(得分:2)

已更新至Swift 3

static func authorizeWithTouchIDIfPossible(){
        let authContext = LAContext()
        var authError : NSError?
        if authContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError) {
            authContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: "I need to see this", reply: { (success, error) in
                if success {
                    print("Touch ID success!")
                    DispatchQueue.main.async {
                        //Do stuff here
                    }
                } else {
                    print("Touch ID failed!")
                }}
            );
        } else {
            print("No local authentication")
        }
    }

答案 4 :(得分:1)

发现它!

以下链接来自Github的名为Shmoopi的用户。 Shmoopi让应用程序测试Swift编程的TouchID。

https://github.com/Shmoopi/Swift-Touch-ID

答案 5 :(得分:0)

Swift 3.0 in:

import UIKit
import LocalAuthentication

class ViewController: UIViewController
{
    @IBAction func TouchBtn(_ sender: AnyObject)
    {
        let context:LAContext = LAContext()

        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error:nil)
        {
            context.evaluatePolicy(LAPolicy.deviceOwnerAuthenticationWithBiometrics, localizedReason:"We Need Your Id", reply:{
                (wasSuccessful,Error) in
                if wasSuccessful
                {
                    print("Was a Sucess")
                }
                else
                {
                    print("Not Logged In")
                }

            })
        }

    }
}

答案 6 :(得分:0)

迅速5:

userNames