首页 > 其他分享 >iOS开发基础101-指纹和面部识别

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

时间:2024-07-16 16:19:53浏览次数:9  
标签:target UIView void iOS 指纹 error action 101 view

在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和手势识别的封装,并展示了如何在实际项目中进行调用和使用。这样可以大大提高代码的复用性和可维护性。

标签:target,UIView,void,iOS,指纹,error,action,101,view
From: https://www.cnblogs.com/chglog/p/18305505

相关文章

  • vue项目中使用axios(自用)
    ————流程参考 在vscode的集成终端中输入npminstallaxios回车安装重启项目(重新运行) 在script中导入axiosimportaxiosfrom'axios'; 在default中的data同级mounted()中按如下获取数据mounted(){//发送异步请求,获取数据//输入thenc......
  • 牛客TOP101:反转链表
    文章目录1.题目描述2.解题思路3.代码实现1.题目描述2.解题思路  简单粗暴的写法,就是从头到尾挨个将所有结点的指向翻转即可。需要注意的是,翻转之后会失去原有指向的结点,所以需要提前保存。  具体做法就是,使用cur标记当前结点,代表这我们将要翻转这个结点......
  • 「杂题乱刷2」CF1015D Walking Between Houses
    duel到的。题目链接CF1015DWalkingBetweenHouses解题思路一道细节题。思路很简单,肯定是一开始能走的越多越好,因此就有一种较好实现的方案,先每次走\(n-1\)格,但由于每次至少要走一格,因此如果不够走了就把能走的都走掉,之后全走\(1\)步即可。时间复杂度\(O(k)\)。参......
  • 题解:CodeForces 1019 A Elections[贪心/三分]
    CodeForces1019AA.Electionstimelimitpertest:2secondsmemorylimitpertest:256megabytesinput:standardinputoutput:standardoutputAsyouknow,majorityofstudentsandteachersofSummerInformaticsSchoolliveinBerlandforthemostparto......
  • Ajax和Axios
    1.1Ajax介绍1.1.1Ajax概述我们前端页面中的数据,如下图所示的表格中的学生信息,应该来自于后台,那么我们的后台和前端是互不影响的2个程序,那么我们前端应该如何从后台获取数据呢?因为是2个程序,所以必须涉及到2个程序的交互,所以这就需要用到我们接下来学习的Ajax技术。Ajax:全......
  • VMware ESXi 8.0U3 macOS Unlocker & OEM BIOS Huawei (华为) 定制版
    VMwareESXi8.0U3macOSUnlocker&OEMBIOSHuawei(华为)FusionServer定制版ESXi8.0U3标准版,Dell(戴尔)、HPE(慧与)、Lenovo(联想)、Inspur(浪潮)、Cisco(思科)、Hitachi(日立)、Fujitsu(富士通)、NEC(日电)、Huawei(华为)、xFusion(超聚变)OEM定制版......
  • Vue.js Ajax(axios)
     Vue.js2.0版本推荐使用axios来完成ajax请求。Axios是一个基于Promise的HTTP库,可以用在浏览器和node.js中。Github开源地址: https://github.com/axios/axios安装方法使用cdn:<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>或<scri......
  • Vue.js Ajax(axios)
    Vue.js2.0版本推荐使用axios来完成ajax请求。Axios是一个基于Promise的HTTP库,可以用在浏览器和node.js中。Github开源地址: https://github.com/axios/axios安装方法使用cdn:<scriptsrc="https://unpkg.com/axios/dist/axios.min.js"></script>或<script......
  • 如何在函数中使用return返回axios的请求结果
    使用场景:在添加学生上课记录的时候,需要先获取学生的剩余课时,需要通过接口获取。所以需要封装一个方法,能够通过接口获取学生的课时数量。解决方案:通过异步解决封装方法的代码如下:constgetStudentCourseCount=async()=>{letnum=0awaitaxios({method:......
  • Cellebrite UFED 4PC 7.69 (Windows) - Android 和 iOS 移动设备取证软件
    CellebriteUFED4PC7.69(Windows)-Android和iOS移动设备取证软件TheIndustryStandardforLawfullyAccessingandCollectingDigitalData请访问原文链接:https://sysin.org/blog/cellebrite-ufed/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgCellebri......