iOS技术集

iOS--React Native 系统二维码扫描插件

2022-09-24  本文已影响0人  Swift社区

一:介绍

React Native (简称RN)是Facebook于2015年4月开源的跨平台移动应用开发框架,是Facebook早先开源的JS框架 React 在原生移动应用平台的衍生产物,目前支持iOS和安卓两大平台。RN使用Javascript语言,类似于HTML的JSX,以及CSS来开发移动应用,因此熟悉Web前端开发的技术人员只需很少的学习就可以进入移动应用开发领域。

在React Native移动平台项目开发中,除了React Native 提供的封装好的部分插件和原声组建外,在实际的项目中还需要使用到很多其他的插件,比如网络请求、数据库、相机、相册、通讯录、视频播放器、浏览器、蓝牙连接、图片处理、消息推送、地图、统计、埋点等等APP开发中需要用到的功能,都为IDE开发平台提供封装好的插件,以便项目开发使用。

另外,这些博文都是来源于我日常开发中的技术总结,在时间允许的情况下,我会针对技术点分别分享iOS、Android两个版本,如果有其他技术点需要,可在文章后留言,我会尽全力帮助大家。这篇文章重点介绍系统二维码扫描插件的开发与使用

二:实现思路分析

二维码扫描插件是将通过调用ScanController封装的功能类实现二维码扫面功能,并通过ScanPlugin类开放scanCode接口提供给H5页面端调用。

具体的实现思路如下:

  1. 新建ScanPlugin类,实现RCTBridgeModule协议

  2. 添加RCT_EXPORT_MODULE()宏

  3. 添加React Native跟控制器

  4. 声明被JavaScript 调用的方法

  5. 新建ZFScanLineAnimation类,实现二维码扫描动画功能

  6. 新建ZFScanController类,实现二维码页面扫描功能

  7. 封装二维码基本调用方法

  8. 实现二维码扫描接口

  9. Javascript调用浏览器方法

三:实现源码分析

实现源码分析是根据上面列出的具体实现思路来为大家解刨内部的实现流程及核心代码分析。

1. 新建ScanPlugin类,实现RCTBridgeModule协议

新建继承NSObject的ScanPlugin类,并实现RCTBridgeModule协议

// ScanPlugin.h
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <UIKit/UIKit.h>
@interface ScanPlugin : NSObject<RCTBridgeModule>
@end

2. 添加RCT_EXPORT_MODULE()宏

为了实现RCTBridgeModule协议,ScanPlugin的类需要包含RCT_EXPORT_MODULE()宏。
并在这个宏里面添加一个参数“ ScanPlugin”用来指定在 JavaScript 中访问这个模块的名字。
如果你不指定,默认就会使用这个 Objective-C 类的名字。
如果类名以 RCT 开头,则 JavaScript 端引入的模块名会自动移除这个前缀。

// ScanPlugin.m
#import "ScanPlugin.h"
@implementation ScanPlugin
RCT_EXPORT_MODULE(ScanPlugin);
@end

3. 添加React Native跟控制器

如果不添加React Native跟控制器,view将不能正常显示出来,实现方法如下:

// ScanPlugin.m
#import <React/RCTUtils.h>

引入<React/RCTUtils.h>之后,在视图初始化或者显示的时候,按照如下方法调用即可

UIViewController *vc = RCTPresentedViewController();

4. 声明被JavaScript 调用的方法

React Native需要明确的声明要给 JavaScript 导出的方法,否则 React Native 不会导出任何方法。下面通过举例来展示声明的方法,通过RCT_EXPORT_METHOD()宏来实现:

// ScanPlugin.m
#import "ScanPlugin.h"
#import <React/RCTUtils.h>
@implementation ScanPlugin
RCT_EXPORT_MODULE(ScanPlugin);

RCT_EXPORT_METHOD(scanCode:(RCTResponseSenderBlock)sucessCallback
                          :(RCTResponseSenderBlock)failCallback)
{
    NSLog(@"调起二维码扫描方法");
}
@end

5. 新建ZFScanLineAnimation类,实现二维码扫描动画功能

在ZFScanController类中实现二维码扫描动画功能,支持条形码,二维码的识别以及返回扫描结果等功能。

核心源码如下:

- (void)startAnimatingWithRect:(CGRect)animationRect InView:(UIView *)parentView Image:(UIImage*)image
{
    if (isAnimationing) {
        return;
    }
    isAnimationing = YES;
    self.animationRect = animationRect;
    down = YES;
    num =0;
    
    CGFloat centery = CGRectGetMinY(animationRect) + CGRectGetHeight(animationRect)/2;
    CGFloat leftx = animationRect.origin.x + 5;
    CGFloat width = animationRect.size.width - 10;
    
    self.frame = CGRectMake(leftx, centery+2*num, width, 2);
    self.image = image;
    [parentView addSubview:self];
    [self startAnimating_UIViewAnimation];
}

6. 新建ZFScanController类,实现二维码页面扫描功能

在新建的ZFScanController类中,定义创建相机、创建输入设备、创建输出设备、创建捕捉类、数据输入预览层、对焦、屏幕方向、提示图等功能属性,代码如下:

@property(nonatomic,strong)AVCaptureDevice *device;//创建相机
@property(nonatomic,strong)AVCaptureDeviceInput *input;//创建输入设备
@property(nonatomic,strong)AVCaptureMetadataOutput *output;//创建输出设备
@property(nonatomic,strong)AVCaptureSession *session;//创建捕捉类
@property(strong,nonatomic)AVCaptureVideoPreviewLayer *preview;//视觉输出预览层
@property (assign, nonatomic) BOOL adjustingFocus;//是否正在对焦

在上面定义的属性下,在startScan方法中实现扫描功能,核心源码如下:

- (void)startScanAnimation
{
    switch (_viewStyle.anmiationStyle)
    {
        case ZFScanViewAnimationStyle_LineMove:
        {
            //线动画
            if (!_scanLineAnimation)
                self.scanLineAnimation = [[ZFScanLineAnimation alloc]init];
            [_scanLineAnimation startAnimatingWithRect:_scanRetangleRect InView:self Image:_viewStyle.animationImage];
        }
            break;
        case ZFScanViewAnimationStyle_NetGrid:
        {
            //网格动画
            if (!_scanNetAnimation)
                self.scanNetAnimation = [[ZFScanNetAnimation alloc]init];
            if(self.viewStyle.HorizontalScan){
                [_scanNetAnimation startAnimatingWithRect:_scanRetangleRect InView:self Image:_viewStyle.animationImage andWithDirection:1];
            }else{
                [_scanNetAnimation startAnimatingWithRect:_scanRetangleRect InView:self Image:_viewStyle.animationImage andWithDirection:0];
            }
            
        }
            break;
        case ZFScanViewAnimationStyle_LineStill:
        {
            if (!_scanLineStill) {
                
                CGRect stillRect = CGRectMake(_scanRetangleRect.origin.x+20,
                                              _scanRetangleRect.origin.y + _scanRetangleRect.size.height/2,
                                              _scanRetangleRect.size.width-40,
                                              2);
                _scanLineStill = [[UIImageView alloc]initWithFrame:stillRect];
                _scanLineStill.image = _viewStyle.animationImage;
            }
            [self addSubview:_scanLineStill];
        }
            
        default:
            break;
    }
    
}
7. 封装二维码基本调用方法

在实现ZFScanController类功能方法后,会在.h文件中开发startScan扫描方法和stopScan停止扫描方法和扫描条形码二维码、返回扫描到的结果、取消扫描、扫描失败等回调方法,以及开发isNeedScanImage是否需要扫码图像,scanView扫码区域,style界面参数等可设置属性。

源码如下:

/**
 开始扫描
 */
-(void)startScan;
/**
 停止扫描
 */
-(void)stopScan;
/**
 扫描条形码二维码
 */
@protocol ZFScanControllerDelegate <NSObject>
/**
 返回扫描到的结果
 
 @param result 扫描二维码结果返回
 */
-(void)scan:(ZFScanController *)scan didFinishWithResult:(NSString *)result;
@optional
/**
 取消扫描
 */
-(void)scanDidCanceled:(ZFScanController *)scan;
/**
 扫描失败
 */
-(void)scan:(ZFScanController *)scan didFailedWithError:(NSDictionary *)errorInfo;
/**
 @brief 是否需要扫码图像
 */
@property (nonatomic, assign) BOOL isNeedScanImage;
/**
 @brief  扫码区域视图,二维码一般都是框
 */
@property (nonatomic,strong)ZFScanView* scanView;
/**
 *  界面效果参数
 */
@property (nonatomic, strong) ZFScanViewStyle *style;
8. 封装二维码扫描接口

在ScanPlugin类中的scanCode方法中,实现ZFScanController的初始化,以及代理方法ZFScanControllerDelegate。

核心源码如下:

#pragma mark delegate
-(void)scanDidCanceled:(ZFScanController *)scan{
    //NSLog(@"cancel");
}
-(void)scan:(ZFScanController *)scan didFailedWithError:(NSDictionary *)errorInfo{
    //NSLog(@"%@",errorInfo);
}
-(void)scan:(ZFScanController *)scan didFinishWithResult:(NSString *)result{
    //NSLog(@"%@",result);
    //原生弹出
    //[self alertWithPrompt:result];
}
#pragma mark 提示
/**
 展示内容
 
 @param prompt 提示
 */
-(void)alertWithPrompt:(NSString *)prompt{
#ifdef __IPHONE_8_0
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:nil message:prompt preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action=[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:action];
    [[self currentViewController] presentViewController:alert animated:YES completion:nil];
#else
    UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:nil message:prompt delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alertview show];
#endif
}
9. Javascript调用浏览器方法

现在从 Javascript 里可以这样调用这个方法:

import { NativeModules } from "react-native";
const ScanPlugin = NativeModules.ScanPlugin;
ScanPlugin.scanCode((msg) => {
                                         Alert.alert(JSON.stringify(msg));

                                         },(err) => {
                                         Alert.alert(JSON.stringify(err));
                                         });
上一篇下一篇

猜你喜欢

热点阅读