IOS开发-指纹识别

1. 简介

iOS 8 SDK向开发者公开了Touch ID指纹识别功能,允许App对用户身份进行本地验证。大家木有发现用指纹登录支付宝,下载appStore应用特方便嘛。使用Touch ID非常简单,下面看下怎么在应用中添加指纹识别登录模块。

  • iPhone 5S 开始支持
  • iOS 8.0 开放了 Touch ID 的接口

2. 代码准备

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    [self inputUserinfo];
}

/// 输入用户信息
- (void)inputUserinfo
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"cancel" message:@"purchase" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"purchase", nil];
    alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

    [alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
    NSLog(@"%zd", buttonIndex);

    if (buttonIndex == 0) 
    {
        return;
    }

    UITextField *usernameText = [alertView textFieldAtIndex:0];
    UITextField *pwdText = [alertView textFieldAtIndex:1];

    if ([usernameText.text isEqualToString:@"zhang"] && [pwdText.text isEqualToString:@"123"]) 
    {
        [self purchase];
    } 
    else 
    {
        [[[UIAlertView alloc] initWithTitle:@"提示" message:@"用户名或密码错误" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:nil, nil] show];
    }
}

/// 购买
- (void)purchase 
{
    NSLog(@"购买");
}

3. 指纹识别

头文件

#import <LocalAuthentication/LocalAuthentication.h>

判断是否支持指纹识别

//1. 检查版本
if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
    [self inputUserinfo];
    return;
}

//2. 检查是否支持指纹识别
LAContext *ctx = [[LAContext alloc] init];

if ([ctx canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:NULL]) 
{
    NSLog(@"支持指纹识别");

    // 异步输入指纹
    [ctx evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:@"购买" reply:^(BOOL success, NSError *error) {
        NSLog(@"%d %@ %@", success, error, [NSThread currentThread]);
        if (success) 
        {
            [self purchase];
        }
        else if (error.code == LAErrorUserFallback) 
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self inputUserinfo];
            });
        }
    }];
    NSLog(@"恭喜您购物成功!");
} else {
    [self inputUserinfo];
}

4. 错误代号

错误 描述
LAErrorAuthenticationFailed 指纹无法识别
LAErrorUserCancel 用户点击了”取消”按钮
LAErrorUserFallback 用户取消,点击了”输入密码”按钮
LAErrorSystemCancel 系统取消,例如激活了其他应用程序
LAErrorPasscodeNotSet 验证无法启动,因为设备上没有设置密码
LAErrorTouchIDNotAvailable 验证无法启动,因为设备上没有 Touch ID
LAErrorTouchIDNotEnrolled 验证无法启动,因为没有输入指纹

你可能感兴趣的:(ios,指纹识别)