文章目录
  1. 1. Feature
  2. 2. ObjC Codes
  3. 3. Swift Codes

Feature

This blog will simply shows the basic usage of Touch ID,one of the device’s system
common fuctions,in both Objective C code and Swift code.
本文将通过 ObjC 和 Swift 分别介绍常用的系统功能–Touch ID指纹识别的基本使用。

Touch ID is one of the new features of iOS 8.0 version.So the device’s operation
system version must be equal or greater than 8.0 .And,the iOS Simulators are unavalable.
Touch ID指纹识别是iOS 8.0的新特性,所以设备的系统版本必须大于等于8.0.而且不能在模拟器上使用该功能。

ObjC Codes

 #import <LocalAuthentication/LocalAuthentication.h>
- (void)authenticateUser {
    if ([[[UIDevice currentDevice]systemVersion] floatValue] < 8.0) {
        //point out that Touch ID in current device's OS is unavalable.

        return;
    }
    LAContext *context = [[LAContext alloc]init];
    NSError *error = nil;
    NSString *message = @"通过验证指纹解锁";

    if ([context canEvaluatePolicy:
         LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {//touch id可用
        [context evaluatePolicy:
         LAPolicyDeviceOwnerAuthenticationWithBiometrics
                localizedReason:message
                          reply:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                NSLog(@"验证成功");
            }else {//验证出错
                [self authenicateErrorWithCode:error.code];
            }
        }];
    }else {
        [self authenicateUnavalableWithCode:error.code];
    }

}

Error code enumeration below.Because of the limit of all versions and sizes of
devices,a few errors are not tested.
以下是异常情况枚举。由于没有各版本各型号的设备,所以有少部分错误类型没有被验证。

- (void)authenicateErrorWithCode:(NSInteger)code {//识别指纹错误
    switch (code) {
        case LAErrorSystemCancel:
        {
            NSLog(@"系统取消验证,如用户切换到其它app");
        }
            break;
            case LAErrorUserCancel:
        {
            NSLog(@"用户取消验证");
        }
            break;
            case LAErrorUserFallback:
        {
            NSLog(@"用户选择输入密码");
        }
            break;
        case LAErrorTouchIDLockout://>=ios 9.0
        {
            NSLog(@"用户多次验证指纹被锁,要求用密码解锁touch id");
        }
            break;
            case LAErrorAppCancel:
        {
            NSLog(@"被其它更高优先级的app取消,如来电");
        }
            break;
        case LAErrorInvalidContext:
        {
            NSLog(@"LAContext对象被从内存中释放了");
        }
            break;
        default:
            [self authenicateUnavalableWithCode:code];
            break;
    }
}

- (void)authenicateUnavalableWithCode:(NSInteger)code {//授权错误
    switch (code) {
        case LAErrorAuthenticationFailed://ios8.0
        {
            NSLog(@"用户未提供有效的验证,如用户多次验证指纹被锁,要求用密码解锁touch id");
        }
            break;
        case LAErrorTouchIDNotAvailable:
        {
            NSLog(@"touch id 不可用,设备不支持");
        }
            break;
        case LAErrorTouchIDNotEnrolled:
        {
            NSLog(@"用户未录入指纹");
        }
            break;
        case LAErrorPasscodeNotSet:
        {
            NSLog(@"未设置密码");
        }
            break;
        default:
            break;
    }
}

Swift Codes

import LocalAuthentication
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated);
        if Float(UIDevice.currentDevice().systemVersion) > 8.0 {            
            self.authenticateUser()
        }
    }


    func authenticateUser() {
        let authenticateContext : LAContext = LAContext()
//        var authenticateContext : LAContext = LAContext()
        var error : NSError?
        if authenticateContext.canEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
            [authenticateContext.evaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics,
                localizedReason: "通过验证home键指纹解锁",
                reply: { (succeed : Bool, evaluatePolicyError : NSError?) -> Void in
                if succeed {
                    print("验证成功")//println("")在swift2.0已禁用
                }else {
                    self.evaluateErrorWithCode(evaluatePolicyError!.code)
                }
            })]
        }else {
            self.evaluateErrorWithCode(error!.code)
        }
    }
    func evaluateErrorWithCode(code : Int) {
        switch code {
        case LAError.AuthenticationFailed.rawValue:
            print("AuthenticationFailed")
        case LAError.UserCancel.rawValue:
            print("UserCancel")
        case LAError.UserFallback.rawValue:
            print("User Fallback")
        case LAError.SystemCancel.rawValue:
            print("System Cancel")
        case LAError.PasscodeNotSet.rawValue:
            print("Passcode Not Set")
        case LAError.TouchIDNotAvailable.rawValue:
            print("TouchID Not Available")
        case LAError.TouchIDNotEnrolled.rawValue:
            print("TouchID Not Enrolled")

//        case LAError.TouchIDLockout.rowValue:
//            print("");
        default:
            print("TouchID Lockout or AppCancel or Invalid Context")
        }

    }

This is my first Swift Demo.The following reference documents should be learn for the
newbie in this demo.

Swift Official Documentation,the primary learning of writing “func“.

Swift 数据类型转换

Difference between var and let

Swift switch usage

Swift enum

Differance between rawValue and hashValue

编写本博客相关环境:Mac OS 10.11.3,Mou 0.8.7,Xcode 7.2 (7C68),iOS 9.2

转自大彬的 iOS开发 Touch ID 系统功能之指纹识别

欢迎大家关注小编的博客 大彬的博客

文章目录
  1. 1. Feature
  2. 2. ObjC Codes
  3. 3. Swift Codes