iOS开发基础101-指纹和面部识别

在iOS开发中,使用FaceID和TouchID可以为用户提供安全的生物识别认证,而手势识别(Gesture Recognition)可以增加用户交互的便利性和灵活性。下面将详细介绍这三种技术,并给出如何封装一个统一的工具类来供外部使用。

一、FaceID与TouchID

1. 设置与配置

在使用FaceID和TouchID之前,需要在项目的Info.plist中添加授权描述。

<key>NSFaceIDUsageDescription</key>
<string>我们需要使用Face ID来验证你的身份</string>
<key>NSFaceIDUsageDescription</key>
<string>我需要使用Face ID来验证用户身份</string>
<key>NSLocalAuthenticationUsageDescription</key>
<string>我们需要使用登录来授权使用应用程序</string>

2. FaceID与TouchID的使用

使用LocalAuthentication框架来进行生物识别认证。

import LocalAuthentication

class BiometricAuthenticator {
    let context = LAContext()
    var error: NSError?

    func authenticateUser(completion: @escaping (String?) -> Void) {
        let reason = "请验证您的身份,以继续使用我们的服务。"
        
        // 检查设备是否支持生物识别
        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            let biometricType = context.biometryType == .faceID ? "FaceID" : "TouchID"
            
            //进行生物识别认证
            context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in
                DispatchQueue.main.async {
                    if success {
                        completion("\(biometricType)认证成功")
                    } else {
                        completion("认证失败: \(error?.localizedDescription)")
                    }
                }
            }
        } else {
            completion("生物识别不可用: \(error?.localizedDescription)")
        }
    }
}

二、手势识别

1. 配置手势识别

手势识别通常通过UIGestureRecognizer及其子类来实现。

import UIKit

class GestureRecognizerHelper {
    
    func addTapGesture(to view: UIView, target: Any, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(tap)
    }
    
    func addSwipeGesture(to view: UIView, target: Any, action: Selector, direction: UISwipeGestureRecognizer.Direction) {
        let swipe = UISwipeGestureRecognizer(target: target, action: action)
        swipe.direction = direction
        view.addGestureRecognizer(swipe)
    }
    
    func addPinchGesture(to view: UIView, target: Any, action: Selector) {
        let pinch = UIPinchGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(pinch)
    }
    
    func addRotationGesture(to view: UIView, target: Any, action: Selector) {
        let rotation = UIRotationGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(rotation)
    }
}

三、封装统一工具类

将FaceID、TouchID和手势识别封装到一个工具类中,便于外部使用。

import LocalAuthentication
import UIKit

class AuthenticationAndGestureHelper {

    // MARK: - FaceID & TouchID
    private let context = LAContext()
    private var error: NSError?
    
    func authenticateUser(completion: @escaping (String?) -> Void) {
        let reason = "请验证您的身份,以继续使用我们的服务。"
        
        // 检查设备是否支持生物识别
        if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            let biometricType = context.biometryType == .faceID ? "FaceID" : "TouchID"
            
            // 进行生物识别认证
            context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { success, error in
                DispatchQueue.main.async {
                    if success {
                        completion("\(biometricType)认证成功")
                    } else {
                        completion("认证失败: \(error?.localizedDescription)")
                    }
                }
            }
        } else {
            completion("生物识别不可用: \(error?.localizedDescription)")
        }
    }
    
    // MARK: - Gesture Recognition
    
    func addTapGesture(to view: UIView, target: Any, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(tap)
    }
    
    func addSwipeGesture(to view: UIView, target: Any, action: Selector, direction: UISwipeGestureRecognizer.Direction) {
        let swipe = UISwipeGestureRecognizer(target: target, action: action)
        swipe.direction = direction
        view.addGestureRecognizer(swipe)
    }
    
    func addPinchGesture(to view: UIView, target: Any, action: Selector) {
        let pinch = UIPinchGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(pinch)
    }
    
    func addRotationGesture(to view: UIView, target: Any, action: Selector) {
        let rotation = UIRotationGestureRecognizer(target: target, action: action)
        view.addGestureRecognizer(rotation)
    }
}

四、使用示例

import UIKit

class ViewController: UIViewController {
    
    let authHelper = AuthenticationAndGestureHelper()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 使用面部识别或者指纹识别
        authHelper.authenticateUser { message in
            if let message = message {
                print(message)
            }
        }
        
        // 添加手势
        authHelper.addTapGesture(to: self.view, target: self, action: #selector(handleTapGesture))
        authHelper.addSwipeGesture(to: self.view, target: self, action: #selector(handleSwipeGesture), direction: .right)
    }
    
    @objc func handleTapGesture() {
        print("Tap Gesture Recognized")
    }
    
    @objc func handleSwipeGesture() {
        print("Swipe Gesture Recognized")
    }
}

对应的oc版本

一、FaceID与TouchID

1. 设置与配置

在使用FaceID和TouchID之前,需要在项目的Info.plist中添加授权描述。

<key>NSFaceIDUsageDescription</key>
<string>我们需要使用Face ID来验证你的身份</string>
<key>NSLocalAuthenticationUsageDescription</key>
<string>我们需要使用登录来授权使用应用程序</string>

2. FaceID与TouchID的使用

使用LocalAuthentication框架来进行生物识别认证。

#import <LocalAuthentication/LocalAuthentication.h>
#import <UIKit/UIKit.h>

@interface BiometricAuthenticator : NSObject

- (void)authenticateUserWithCompletion:(void (^)(NSString *))completion;

@end

@implementation BiometricAuthenticator

- (void)authenticateUserWithCompletion:(void (^)(NSString *))completion {
    LAContext *context = [[LAContext alloc] init];
    NSError *error = nil;
    NSString *reason = @"请验证您的身份,以继续使用我们的服务。";
    
    // 检查设备是否支持生物识别
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {
        NSString *biometricType = context.biometryType == LABiometryTypeFaceID ? @"FaceID" : @"TouchID";
        
        // 进行生物识别认证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    completion([NSString stringWithFormat:@"%@认证成功", biometricType]);
                } else {
                    completion([NSString stringWithFormat:@"认证失败: %@", error.localizedDescription]);
                }
            });
        }];
    } else {
        completion([NSString stringWithFormat:@"生物识别不可用: %@", error.localizedDescription]);
    }
}

@end

二、手势识别

1. 配置手势识别

手势识别通常通过UIGestureRecognizer及其子类来实现。

#import <UIKit/UIKit.h>

@interface GestureRecognizerHelper : NSObject

- (void)addTapGestureToView:(UIView *)view target:(id)target action:(SEL)action;
- (void)addSwipeGestureToView:(UIView *)view target:(id)target action:(SEL)action direction:(UISwipeGestureRecognizerDirection)direction;
- (void)addPinchGestureToView:(UIView *)view target:(id)target action:(SEL)action;
- (void)addRotationGestureToView:(UIView *)view target:(id)target action:(SEL)action;

@end

@implementation GestureRecognizerHelper

- (void)addTapGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:tap];
}

- (void)addSwipeGestureToView:(UIView *)view target:(id)target action:(SEL)action direction:(UISwipeGestureRecognizerDirection)direction {
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:target action:action];
    swipe.direction = direction;
    [view addGestureRecognizer:swipe];
}

- (void)addPinchGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:pinch];
}

- (void)addRotationGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:rotation];
}

@end

三、封装统一工具类

将FaceID、TouchID和手势识别封装到一个工具类中,便于外部使用。

#import <LocalAuthentication/LocalAuthentication.h>
#import <UIKit/UIKit.h>

@interface AuthenticationAndGestureHelper : NSObject

// FaceID & TouchID
- (void)authenticateUserWithCompletion:(void (^)(NSString *message))completion;

// Gesture Recognition
- (void)addTapGestureToView:(UIView *)view target:(id)target action:(SEL)action;
- (void)addSwipeGestureToView:(UIView *)view target:(id)target action:(SEL)action direction:(UISwipeGestureRecognizerDirection)direction;
- (void)addPinchGestureToView:(UIView *)view target:(id)target action:(SEL)action;
- (void)addRotationGestureToView:(UIView *)view target:(id)target action:(SEL)action;

@end

@implementation AuthenticationAndGestureHelper {
    LAContext *_context;
    NSError *_error;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _context = [[LAContext alloc] init];
    }
    return self;
}

- (void)authenticateUserWithCompletion:(void (^)(NSString *message))completion {
    NSString *reason = @"请验证您的身份,以继续使用我们的服务。";
    
    if ([_context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&_error]) {
        NSString *biometricType = _context.biometryType == LABiometryTypeFaceID ? @"FaceID" : @"TouchID";
        
        [_context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:reason reply:^(BOOL success, NSError * _Nullable error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (success) {
                    completion([NSString stringWithFormat:@"%@认证成功", biometricType]);
                } else {
                    completion([NSString stringWithFormat:@"认证失败: %@", error.localizedDescription]);
                }
            });
        }];
    } else {
        completion([NSString stringWithFormat:@"生物识别不可用: %@", _error.localizedDescription]);
    }
}

- (void)addTapGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:tap];
}

- (void)addSwipeGestureToView:(UIView *)view target:(id)target action:(SEL)action direction:(UISwipeGestureRecognizerDirection)direction {
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:target action:action];
    swipe.direction = direction;
    [view addGestureRecognizer:swipe];
}

- (void)addPinchGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:pinch];
}

- (void)addRotationGestureToView:(UIView *)view target:(id)target action:(SEL)action {
    UIRotationGestureRecognizer *rotation = [[UIRotationGestureRecognizer alloc] initWithTarget:target action:action];
    [view addGestureRecognizer:rotation];
}

@end

四、使用示例

#import "ViewController.h"
#import "AuthenticationAndGestureHelper.h"

@interface ViewController ()

@property (nonatomic, strong) AuthenticationAndGestureHelper *authHelper;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.authHelper = [[AuthenticationAndGestureHelper alloc] init];
    
    // 使用面部识别或者指纹识别
    [self.authHelper authenticateUserWithCompletion:^(NSString *message) {
        if (message) {
            NSLog(@"%@", message);
        }
    }];
    
    // 添加手势
    [self.authHelper addTapGestureToView:self.view target:self action:@selector(handleTapGesture)];
    [self.authHelper addSwipeGestureToView:self.view target:self action:@selector(handleSwipeGesture) direction:UISwipeGestureRecognizerDirectionRight];
}

- (void)handleTapGesture {
    NSLog(@"Tap Gesture Recognized");
}

- (void)handleSwipeGesture {
    NSLog(@"Swipe Gesture Recognized");
}

@end

通过上述代码示例,我们实现了对FaceID、TouchID和手势识别的封装,并展示了如何在实际项目中进行调用和使用。这样可以大大提高代码的复用性和可维护性。

posted @ 2024-07-16 16:17  Mr.陳  阅读(13)  评论(0编辑  收藏  举报