How to use Swift to implement Touch ID verification in iOS 8?

Source: Internet
Author: User

How to use Swift to implement Touch ID verification in iOS 8?

IOS8 opens many APIs, including HomeKit and HealthKit. Here we want to talk about Touch ID verification for one of them.

In the past, apps were used to protect users' private content. Only passwords can be set and entered. The iPhone can only use Touch ID to easily unlock its own apps. It's really urgent. Now we can also be cool. When you open an app that uses Touch ID authentication to view the content, you can only put your finger on the Home key to verify your identity. The fingerprint verified in the app is the user's fingerprint on the mobile phone. Yes, your app does not require the user to enter the verification fingerprint again. So it is very convenient to use. But you need to make other preparations. Just like unlocking an iPhone without entering a password. If a user does not enable the Touch ID app, isn't it?

As described in, this project is implemented using Swift. If you are not familiar with swift, you need to make up your mind slightly.

Let's take a look at the results.

See it. You just need to put your thumb on the Home key to unlock it.

The interface layout is as follows:

Click the button to trigger verification. After clicking the Authenticate button, the verification prompt for the first image is displayed.

Okay, go to the topic.

Create a project first. You can use your name or whatever it is. But for programming language, select Swift here. Since xcode6.0.1 already claims to provide full support for swift. Then we will go directly to swift. You can call the existing ObjC code through the mechanism provided by Apple. Five words: this is not a problem. Besides, swfit can save a lot of code. You can set the default options for other projects. That is, we can simply use storyboard to save time. Although there is actually no interface element to omit...

In the created Project, select Build Phases. Introduce the framework of LocalAuthentication into the project. You can set the project here.

Import the framework introduced 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 for creating a button. First, create a button of the same type as the system.UIButton. buttonWithType (UIButtonType. System)The returned value is an AnyObject object. Therefore, the type must be forcibly converted to UIButon. AnyObject and Any types are frequently encountered. The main purpose is to be compatible with the code before ObjC. Therefore, the is or as operator is often used to detect and force type conversion.

  • AnyObject is an instance of any class type.
  • Any is an instance of Any type.

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

The code for creating UIButton is no big difference from the previous OC method. But changed to the swift syntax. With the button, you can set the event handling method for clicking the button. Remember not to addTarget:

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

Let's take a look at the addTarget statement:Func addTarget (target: AnyObject ?, Action: Selector, forControlEvents controlEvents: UIControlEvents)In the call to the method, we can see that self is the target of AnyObject. You don't need to say much. The following action is a Selector struct ). We initialized a Selector struct during the call. This parameter can also be used to directly give the action string without initializing the Selector struct. This involves a knowledge point for automatic type conversion. The Selector constructor must provide a string as the parameter. Therefore, if a string is provided directly, the compiler will initialize the Selector struct as the parameter. The last colon (:) In the Selector string is the same as that in ObjC. The colon indicates that the method has a parameter. Finally, it is the enumeration type of UIControlEvents. It is not as long as it is written 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 authenticatation", message: "", delegate: nil, cancelButtonTitle: "Cancel") 
  21.         } 
  22.     } 

The most important thing here is the Touch ID verification function.Var laContext = LAContext ()Type inference is used. The type of the instance to which the variable is initialized. This variable is automatically inferred to be of that type.Var authError: NSError?Class inference and optional value. Optional value adds a question mark after the type. Indicates that the value can be an instance or nil. Note: swift's nil and ObjC's nil are two different things. The nil of ObjC is a null value of the reference type. Swift's nil indicates that this variable has no value and can be of any reference type.Var errorReason = "keep things secret"This string must be realistic on the interface. So you must never leave it empty!

LaContext. canEvaluatePolicy (LAPolicy. DeviceOwnerAuthenticationWithBiometrics, error: & authError)Check whether the device can use biometrics to authenticate the identity. Is to see if the fingerprint can be unlocked. No hardware or fingerprint is set for the hardware. Okay. If you have set the fingerprint, you can unlock it.

 
 
  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 subsequent replay parameter is a closure with an empty return value. The closure parameters are bool and NSError! The general form of closure is{(Parameter 1, parameter 2)-> return value type in // code}SuccessReturn the verification result. If the job is successful, the return value is true or false ). In this case, replace the println ("succeed") or println ("failed") statement based on whether the verification succeeds or fails to implement the functions you need. For example, enter the function details page of the app and use Touch ID to protect the information. If the verification fails, go to the password verification section. In this way, you can enter the function of the app by entering the password when fingerprint verification fails.

That's it. Try writing a project!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.