现在大部分的app都会有这样的一个功能就是二维码扫描,这个功能算得上是一个常见的辅助功能,那么如何来实现呢?这里小编来给大家详细介绍一下如何简单来实现这个功能。
首先,二维码扫描要用到相机,我们需要导入AVFoundation框架,例如:我创建一个QRCodeScanViewController的控制器类,导入AVFoundation,如下:
#import "QRCodeScanViewController.h"
#import <AVFoundation/AVFoundation.h>
接下来,我们声明几个需要的属性
@interface QRCodeScanViewController () <AVCaptureMetadataOutputObjectsDelegate>
//采集的设备
@property (strong,nonatomic) AVCaptureDevice * device;
//设备的输入
@property (strong,nonatomic) AVCaptureDeviceInput * input;
//输出
@property (strong,nonatomic) AVCaptureMetadataOutput * output;
//采集流
@property (strong,nonatomic) AVCaptureSession * session;
//窗口
@property (strong,nonatomic) AVCaptureVideoPreviewLayer * previewLayer;
//扫描框
@property (nonatomic, strong) UIView * view_bg;
//扫描线
@property (nonatomic, strong) CALayer * layer_scanLine;
//提示语
@property (nonatomic, strong) UILabel * lab_word;
//扫描线定时器
@property (nonatomic, strong) NSTimer * timer;
@end
这里要注意的是需要遵从AVCaptureMetadataOutputObjectsDelegate这个代理协议,扫描结果主要是在代理方法中获取。
下面是实例化设备并进行扫描的核心代码,可以在viewDidLoad中直接调用该方法即可。
#pragma mark - start saomiao
- (void)startScan {
// Device 实例化设备 //获取摄像设备
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input 设备输入 //创建输入流
_input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
// Output 设备的输出 //创建输出流
_output = [[AVCaptureMetadataOutput alloc]init];
//设置代理 在主线程里刷新
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session //初始化链接对象
_session = [[AVCaptureSession alloc]init];
//高质量采集率
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:self.input])
{
[_session addInput:self.input];
}
if ([_session canAddOutput:self.output])
{
[_session addOutput:self.output];
}
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
// 二维码类型 AVMetadataObjectTypeQRCode
_output.metadataObjectTypes =@[AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeUPCECode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code,
AVMetadataObjectTypePDF417Code,
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypeInterleaved2of5Code,
AVMetadataObjectTypeITF14Code,
AVMetadataObjectTypeDataMatrixCode];
// Preview 扫描窗口设置
_previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
_previewLayer.frame = CGRectMake(0, 0, Screen_Width, Screen_Height - 64);
//设置扫描的范围,假如屏幕宽为width,屏幕高为height,下面参数含义为:
//0.15意思为距离屏幕左右距离各为0.15*width;
//0.25意思为距离屏幕上下距离各为0.25*height;
//0.7意思为扫描横向范围为0.7*width;
//0.5意思为扫描纵向范围为0.5*height;
_output.rectOfInterest = CGRectMake(0.15, 0.25, 0.7, 0.5);
[self.view.layer insertSublayer:_previewLayer atIndex:0];
//添加扫描框和扫描线和提示语
[self addSubviews];
//设置约束
[self makeConstraintsForUI];
// Start 开始扫描 //开始捕获
[_session startRunning];
//扫描线开始动画
self.timer.fireDate = [NSDate distantPast];
}
下面是添加扫描框和线等控件的代码方法
#pragma mark - add subviews
- (void)addSubviews {
[self.view addSubview:self.view_bg];
[self.view addSubview:self.lab_word];
//这里需要注意的是扫描线用到了动画效果是用的layer
[_view_bg.layer addSublayer:self.layer_scanLine];
}
#pragma mark - make constraints
- (void)makeConstraintsForUI {
[_view_bg mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(0.7 * Screen_Width, 0.5 * (Screen_Height - 64)));
make.left.mas_equalTo(@(0.15 * Screen_Width));
make.top.mas_equalTo(@(0.25 * (Screen_Height - 64) - 32));
}];
[_lab_word mas_makeConstraints:^(MASConstraintMaker *make) {
make.size.mas_equalTo(CGSizeMake(Screen_Width, 21));
make.left.mas_equalTo(@0);
make.top.mas_equalTo(_view_bg.mas_bottom).with.offset(20);
}];
}
#pragma mark - setter and getter
- (UIView *)view_bg {
if (!_view_bg) {
_view_bg = [[UIView alloc] init];
_view_bg.layer.borderColor = [UIColor whiteColor].CGColor;
_view_bg.layer.borderWidth = 1.0;
}
return _view_bg;
}
- (CALayer *)layer_scanLine {
if (!_layer_scanLine) {
CALayer * layer = [[CALayer alloc] init];
layer.bounds = CGRectMake(0, 0, 0.7 * Screen_Width, 1);
layer.backgroundColor = [UIColor greenColor].CGColor;
//起点
layer.position = CGPointMake(0, 0);
//定位点
layer.anchorPoint = CGPointMake(0, 0);
_layer_scanLine = layer;
}
return _layer_scanLine;
}
- (UILabel *)lab_word {
if (!_lab_word) {
_lab_word = [[UILabel alloc] init];
_lab_word.textAlignment = NSTextAlignmentCenter;
_lab_word.textColor = [UIColor whiteColor];
_lab_word.font = H13;
_lab_word.text = @"将二维码/条码放入框内,即可进行扫描";
}
return _lab_word;
}
- (NSTimer *)timer {
if (!_timer) {
_timer = [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(scanLineMove) userInfo:nil repeats:YES];
[_timer fire];
}
return _timer;
}
接下来实现定时器方法,即对扫描线添加动画:
#pragma mark - timer event
- (void)scanLineMove {
CABasicAnimation * animation = [[CABasicAnimation alloc] init];
//告诉系统要执行什么样的动画
animation.keyPath = @"position";
//设置通过动画 layer从哪到哪
animation.fromValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
animation.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0.5 * (Screen_Height - 64))];
//动画时间
animation.duration = 4.0;
//设置动画执行完毕之后不删除动画
animation.removedOnCompletion = NO;
//设置保存动画的最新动态
animation.fillMode = kCAFillModeForwards;
//添加动画到layer
[self.layer_scanLine addAnimation:animation forKey:nil];
}
OK!到这里所有需要的属性都已经设置好了,接下来就是实现代理方法,所得到的结果就在这个方法里边,需要对结果做的操作都可以在此进行,这里小编就只是把得到的结果以提示框的形式展示了出来,实际应用中如果需要做其他的操作都可以根据得到的结果类型等做出相应的操作。
#pragma mark - AVCaptureMetadataOutputObjects delegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
//得到解析到的结果
NSString * stringValue;
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject * metadataObject = metadataObjects.firstObject;
stringValue = metadataObject.stringValue;
}
//停止扫描
[_session stopRunning];
//扫描线定时器停止
self.timer.fireDate = [NSDate distantFuture];
//创建提示框
UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"结果:%@", stringValue] preferredStyle:UIAlertControllerStyleAlert];
//取消扫描
UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[_previewLayer removeFromSuperlayer];
//释放定时器并置空
[self.timer invalidate];
_timer = nil;
//提示框返回
[self dismissViewControllerAnimated:YES completion:nil];
//跳转回之前界面(从当前扫描界面退出)
[self.navigationController popViewControllerAnimated:YES];
}];
//重新开始扫描
UIAlertAction * actionReStart = [UIAlertAction actionWithTitle:@"重新扫描" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//开始扫描
[_session startRunning];
//定时器开始
self.timer.fireDate = [NSDate distantPast];
}];
//将提示action添加到alertController控制器上
[alertController addAction:actionCancel];
[alertController addAction:actionReStart];
[self presentViewController:alertController animated:YES completion:nil];
}
差点忘了最后一点,Xcode8.0需要在info.plist文件中需要添加Privacy - Camera Usage Description字段,Xcode8.0以下版本同样需要在info.plist文件中添加类似字段。
最后,还是希望能够帮到有需要的朋友们,如果有哪里不是很清楚的地方可以提问小编,小编会在看到的第一时间回复。愿同是程序猿的我们能够共同学习进步,在开发的道路上越走越远!