How to implement Touch ID verification in iOS 8 using Swift

How to implement Touch ID verification in iOS 8 using Swift

iOS8 opens many APIs, including HomeKit, HealthKit, etc. What we are going to talk about here is Touch ID verification, one of them.

In the past, the only way to protect users’ privacy with apps was to set and enter passwords. It was frustrating to see that only the iPhone itself could use Touch ID to unlock conveniently and coolly, but your own app couldn’t. Now we can be cool too. When users open an app that uses Touch ID authentication to view content, they can only place their finger on the Home button to verify their identity. The fingerprint verified in the app is the user’s fingerprint in the phone. Yes, your app does not require users to enter the fingerprint for verification again. So it is still very convenient to use. But you have to make other preparations. Just like unlocking an iPhone requires entering a password. If the user does not turn on Touch ID, our app cannot be blinded, right?

As the title says, this project is implemented using Swift. If you are not familiar with Swift, you may need to brush up a little.

Having said so much, let’s see the results.

See? Just place your thumb on the Home button to unlock it.

The interface layout is as follows:

Here, verification is triggered by clicking a button. After clicking the Authenticate button, the verification prompt in the first picture pops up.

Okay, let’s get to the point.

First, create a project. You can choose any name you want. But for the programming language, you need to choose Swift. Since xcode6.0.1 claims to provide full support for Swift, let's just use Swift. If that doesn't work, you can also call the existing ObjC code through the mechanism provided by Apple. In short, five words: it's not a big deal. And swfit can save a lot of code. Keep the default selections in other parts of the project. In other words, we can save some trouble and just use storyboard. Although there are actually no interface elements that can be omitted...

In the created project, select Build Phases. Import the LocalAuthentication framework into the project. That’s all the project settings are.

Import the framework in the code.

  1. import LocalAuthentication

Next, create a button:

  1. var authButton: UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton
  2. authButton.frame = CGRect(x: 100, y: screenHeight / 2, width: 100, height: 30)
  3. authButton.setTitle( "Authenticate" , forState: UIControlState.Normal)

Here is the code to create a button. First, create a button of the same type as the system. UIButton.buttonWithType(UIButtonType.System) returns an object of type AnyObject, so you need to force the type conversion to UIButton. AnyObject and Any are often encountered. This is mainly for compatibility with the code before ObjC. Therefore, the is or as operator is often used to detect and force type conversion.

  • AnyObject refers to any instance of a class type
  • Any refers to any instance of a type

For example, the AnyObject array can store any instance of a class type. These instances are all of the same class type. The Any array can store instances of any type, and the types of these array members are not necessarily the same.

The code to create a UIButton is not much different from the previous OC method. It just uses Swift syntax. After you have a button, you should set the method to handle the button click event. Remember addTarget:

  1. authButton.addTarget(self, action: Selector( "addPassAction:" ), forControlEvents: UIControlEvents.TouchUpInside)

Let's take a look at the declaration of addTarget first: func addTarget(target: AnyObject?, action: Selector, forControlEvents controlEvents: UIControlEvents) In the corresponding method call, you can see that self is the target of AnyObject, so there is no need to say more. The action behind it is a Selector structure (struct). We initialized a Selector structure when calling it. This parameter can also directly give the action string without initializing the Selector structure. This involves a knowledge point of automatic type conversion. The Selector constructor needs to provide a string as a parameter, so if the string is given directly, the compiler will directly use this string as a parameter to initialize a Selector structure. In the Selector string content, *** is a colon ":", which is the same as the writing method of ObjC. The colon indicates that the method has a parameter. *** is the enumeration type of UIControlEvents. Here you don't have to write so long every time.

Then, implement Selector:

  1. func addPassAction(sender:UIButton!){
  2. println( "add pass action" )
  3.   
  4. var laContext = LAContext()
  5. var authError : NSError?
  6. var errorReason = "keep things secret"  
  7.   
  8. if laContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &authError){
  9. laContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: errorReason, reply: {
  10. (success, error) in
  11. if success {
  12. println( "succeed" )
  13. }
  14. else {
  15. println( "failed" )
  16. }
  17. })
  18. }
  19. else {
  20. var alert = UIAlertView(title: "Can not do authentication" , message: "" , delegate: nil, cancelButtonTitle: "Cancel" )
  21. }
  22. }

The most important thing here is the Touch ID verification function. var laContext = LAContext() uses type inference. The variable is automatically inferred to be of the type of the instance that initializes the variable. var authError : NSError? Type inference and optional value. An optional value is a question mark after the type. It means that this value can be an instance or nil. Note: nil in Swift and nil in ObjC are two different things. ObjC's nil is an empty value of a reference type. Swift's nil means that this variable has no value, whether it is a reference type or not. var errorReason = "keep things secret" This string is to be displayed in the interface. So it must not be empty!

laContext.canEvaluatePolicy (LAPolicy .DeviceOwnerAuthenticationWithBiometrics , error: &authError) Checks whether the device can use biometrics to authenticate. It is to see if the fingerprint can be unlocked. If there is no hardware, or the fingerprint is not set up for the hardware, it cannot be authenticated. OK, if the fingerprint has been set up, then it can be unlocked.

  1. laContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, localizedReason: errorReason, reply: {
  2.  
  3. (success, error) in
  4.  
  5. if success {
  6.  
  7. println( "succeed" )
  8.  
  9. }
  10.  
  11. else {
  12.  
  13. println( "failed" )
  14.  
  15. }
  16.  
  17. })

The replay parameter behind is a closure with an empty return value. The parameters of this closure are bool and NSError! The general form of closure is {(parameter 1, parameter 2)->return value type in //code} success returns the verification result, success or failure (true or false). At this time, according to the success or failure of the verification, replace the println("succeed") or println("failed") statement to implement the function you need to implement. For example, enter the function details page of the app and other information protected by Touch ID. If verification cannot be performed, jump to the password verification part. In this way, the user can enter the function part of the app by entering the password when fingerprint verification cannot be performed.

That’s it. Let’s write a project and give it a try!

<<:  From Objective-C to Swift: Some Thoughts and Opinions

>>:  Detailed explanation of using Android HOOK tool Cydia Substrate

Recommend

Apps with data - data expressions on mobile phones

Previously, I studied the best way to express dat...

If skin care products have good ingredients, will they definitely be effective?

Review expert: Li Xixi, PhD in Biomedical Enginee...

IBM versus Amazon Cloud Computing: Can Big Blue disrupt itself?

After ten consecutive quarters of shrinking perfo...

Drawing like humans, GT team develops graffiti robot system

Recently, a research team from Georgia Institute ...

It is enough for Toutiao information flow delivery and strategy optimization

Placement From June to November 2016, the consump...

Tips you need to know about live streaming

In 2019, "Li Jiaqi" and "Viya"...