闫晓菲 發表於 2024-7-16 16:17:00

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

<p>在iOS开发中,使用FaceID和TouchID可以为用户提供安全的生物识别认证,而手势识别(Gesture Recognition)可以增加用户交互的便利性和灵活性。下面将详细介绍这三种技术,并给出如何封装一个统一的工具类来供外部使用。</p>
<h3 id="一faceid与touchid">一、FaceID与TouchID</h3>
<h4 id="1-设置与配置">1. 设置与配置</h4>
<p>在使用FaceID和TouchID之前,需要在项目的Info.plist中添加授权描述。</p>
<pre><code class="language-xml">&lt;key&gt;NSFaceIDUsageDescription&lt;/key&gt;
&lt;string&gt;我们需要使用Face ID来验证你的身份&lt;/string&gt;
&lt;key&gt;NSFaceIDUsageDescription&lt;/key&gt;
&lt;string&gt;我需要使用Face ID来验证用户身份&lt;/string&gt;
&lt;key&gt;NSLocalAuthenticationUsageDescription&lt;/key&gt;
&lt;string&gt;我们需要使用登录来授权使用应用程序&lt;/string&gt;
</code></pre>
<h4 id="2-faceid与touchid的使用">2. FaceID与TouchID的使用</h4>
<p>使用LocalAuthentication框架来进行生物识别认证。</p>
<pre><code class="language-swift">import LocalAuthentication

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

    func authenticateUser(completion: @escaping (String?) -&gt; Void) {
      let reason = "请验证您的身份,以继续使用我们的服务。"
      
      // 检查设备是否支持生物识别
      if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &amp;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)")
      }
    }
}
</code></pre>
<h3 id="二手势识别">二、手势识别</h3>
<h4 id="1-配置手势识别">1. 配置手势识别</h4>
<p>手势识别通常通过<code>UIGestureRecognizer</code>及其子类来实现。</p>
<pre><code class="language-swift">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)
    }
}
</code></pre>
<h3 id="三封装统一工具类">三、封装统一工具类</h3>
<p>将FaceID、TouchID和手势识别封装到一个工具类中,便于外部使用。</p>
<pre><code class="language-swift">import LocalAuthentication
import UIKit

class AuthenticationAndGestureHelper {

    // MARK: - FaceID &amp; TouchID
    private let context = LAContext()
    private var error: NSError?
   
    func authenticateUser(completion: @escaping (String?) -&gt; Void) {
      let reason = "请验证您的身份,以继续使用我们的服务。"
      
      // 检查设备是否支持生物识别
      if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &amp;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)
    }
}
</code></pre>
<h3 id="四使用示例">四、使用示例</h3>
<pre><code class="language-swift">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")
    }
}
</code></pre>
<h2 id="对应的oc版本">对应的oc版本</h2>
<h3 id="一faceid与touchid-1">一、FaceID与TouchID</h3>
<h4 id="1-设置与配置-1">1. 设置与配置</h4>
<p>在使用FaceID和TouchID之前,需要在项目的Info.plist中添加授权描述。</p>
<pre><code class="language-xml">&lt;key&gt;NSFaceIDUsageDescription&lt;/key&gt;
&lt;string&gt;我们需要使用Face ID来验证你的身份&lt;/string&gt;
&lt;key&gt;NSLocalAuthenticationUsageDescription&lt;/key&gt;
&lt;string&gt;我们需要使用登录来授权使用应用程序&lt;/string&gt;
</code></pre>
<h4 id="2-faceid与touchid的使用-1">2. FaceID与TouchID的使用</h4>
<p>使用LocalAuthentication框架来进行生物识别认证。</p>
<pre><code class="language-objective-c">#import &lt;LocalAuthentication/LocalAuthentication.h&gt;
#import &lt;UIKit/UIKit.h&gt;

@interface BiometricAuthenticator : NSObject

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

@end

@implementation BiometricAuthenticator

- (void)authenticateUserWithCompletion:(void (^)(NSString *))completion {
    LAContext *context = [ init];
    NSError *error = nil;
    NSString *reason = @"请验证您的身份,以继续使用我们的服务。";
   
    // 检查设备是否支持生物识别
    if () {
      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();
                } else {
                  completion();
                }
            });
      }];
    } else {
      completion();
    }
}

@end
</code></pre>
<h3 id="二手势识别-1">二、手势识别</h3>
<h4 id="1-配置手势识别-1">1. 配置手势识别</h4>
<p>手势识别通常通过<code>UIGestureRecognizer</code>及其子类来实现。</p>
<pre><code class="language-objective-c">#import &lt;UIKit/UIKit.h&gt;

@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 = [ initWithTarget:target action:action];
    ;
}

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

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

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

@end
</code></pre>
<h3 id="三封装统一工具类-1">三、封装统一工具类</h3>
<p>将FaceID、TouchID和手势识别封装到一个工具类中,便于外部使用。</p>
<pre><code class="language-objective-c">#import &lt;LocalAuthentication/LocalAuthentication.h&gt;
#import &lt;UIKit/UIKit.h&gt;

@interface AuthenticationAndGestureHelper : NSObject

// FaceID &amp; 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 = ;
    if (self) {
      _context = [ init];
    }
    return self;
}

- (void)authenticateUserWithCompletion:(void (^)(NSString *message))completion {
    NSString *reason = @"请验证您的身份,以继续使用我们的服务。";
   
    if () {
      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();
                } else {
                  completion();
                }
            });
      }];
    } else {
      completion();
    }
}

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

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

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

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

@end
</code></pre>
<h3 id="四使用示例-1">四、使用示例</h3>
<pre><code class="language-objective-c">#import "ViewController.h"
#import "AuthenticationAndGestureHelper.h"

@interface ViewController ()

@property (nonatomic, strong) AuthenticationAndGestureHelper *authHelper;

@end

@implementation ViewController

- (void)viewDidLoad {
    ;
   
    self.authHelper = [ init];
   
    // 使用面部识别或者指纹识别
    [self.authHelper authenticateUserWithCompletion:^(NSString *message) {
      if (message) {
            NSLog(@"%@", message);
      }
    }];
   
    // 添加手势
    ;
    ;
}

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

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

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


</div>
<div id="MySignature" role="contentinfo">
    将来的你会感谢今天如此努力的你!
版权声明:本文为博主原创文章,未经博主允许不得转载。<br><br>
来源:https://www.cnblogs.com/chglog/p/18305505
頁: [1]
查看完整版本: iOS开发基础101-指纹和面部识别