ios原生二维码扫描

所属分类: 软件编程 / IOS 阅读数: 670
收藏 0 赞 0 分享

做iOS的二维码扫描,有两个第三方库可以选择,ZBar和ZXing。今天要介绍的是iOS7.0后AVFoundation框架提供的原生二维码扫描。

首先需要添加AVFoundation.framework框架到你工程中build phase的"Link Binary With Libraries"之下,然后就可以开始了。

一、做好准备工作,搭建UI

UI效果如图

IBOutlet、IBAction如下:

@property (weak, nonatomic) IBOutlet UIView *viewPreview;
@property (weak, nonatomic) IBOutlet UILabel *lblStatus;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
- (IBAction)startStopReading:(id)sender;

接下来就都是代码的事情了

二、控制器ViewController.h

首先导入AVFoundation框架

#import <AVFoundation/AVFoundation.h>

然后控制器实现 AVCaptureMetadataOutputObjectsDelegate协议

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>

整体property如下:

@property (strong, nonatomic) UIView *boxView;
@property (nonatomic) BOOL isReading;
@property (strong, nonatomic) CALayer *scanLayer;
-(BOOL)startReading;
-(void)stopReading;

//捕捉会话

@property (nonatomic, strong) AVCaptureSession *captureSession;

//展示layer

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *videoPreviewLayer;

然后在ViewDidLoad方法中初始化

- (void)viewDidLoad {
  [super viewDidLoad];

  _captureSession = nil;
   _isReading = NO;
  
}

接下来实现startReading方法(这可就是重点咯)

- (BOOL)startReading {
 NSError *error;
 //1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
 AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
 //2.用captureDevice创建输入流
 AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
 if (!input) {
  NSLog(@"%@", [error localizedDescription]);
  return NO;
 }
 //3.创建媒体数据输出流
 AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
 //4.实例化捕捉会话
 _captureSession = [[AVCaptureSession alloc] init];
 //4.1.将输入流添加到会话
 [_captureSession addInput:input];
 //4.2.将媒体输出流添加到会话中
 [_captureSession addOutput:captureMetadataOutput];
 //5.创建串行队列,并加媒体输出流添加到队列当中
 dispatch_queue_t dispatchQueue;
 dispatchQueue = dispatch_queue_create("myQueue", NULL);
 //5.1.设置代理
 [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
 //5.2.设置输出媒体数据类型为QRCode
 [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
 //6.实例化预览图层
 _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
 //7.设置预览图层填充方式
 [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
 //8.设置图层的frame
 [_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
 //9.将图层添加到预览view的图层上
 [_viewPreview.layer addSublayer:_videoPreviewLayer];
 //10.设置扫描范围
 captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
 //10.1.扫描框
 _boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2f, _viewPreview.bounds.size.height * 0.2f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.height - _viewPreview.bounds.size.height * 0.4f)];
 _boxView.layer.borderColor = [UIColor greenColor].CGColor;
 _boxView.layer.borderWidth = 1.0f;
 [_viewPreview addSubview:_boxView];
 //10.2.扫描线
 _scanLayer = [[CALayer alloc] init];
 _scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
 _scanLayer.backgroundColor = [UIColor brownColor].CGColor;
 [_boxView.layer addSublayer:_scanLayer];
 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.2f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
 [timer fire];

 //10.开始扫描
 [_captureSession startRunning];
 return YES;
}

实现AVCaptureMetadataOutputObjectsDelegate协议方法

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
 //判断是否有数据
 if (metadataObjects != nil && [metadataObjects count] > 0) {
  AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
  //判断回传的数据类型
  if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
   [_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
   [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
   _isReading = NO;
  }
 }
}

实现计时器方法moveScanLayer:(NSTimer *)timer

- (void)moveScanLayer:(NSTimer *)timer
{
 CGRect frame = _scanLayer.frame;
 if (_boxView.frame.size.height < _scanLayer.frame.origin.y) {
  frame.origin.y = 0;
  _scanLayer.frame = frame;
 }else{
  frame.origin.y += 5;
  [UIView animateWithDuration:0.1 animations:^{
   _scanLayer.frame = frame;
  }];
 }
}

实现开始和停止方法

- (IBAction)startStopReading:(id)sender {
  if (!_isReading) {
   if ([self startReading]) {
    [_startBtn setTitle:@"Stop" forState:UIControlStateNormal];
    [_lblStatus setText:@"Scanning for QR Code"];
   }
  }
  else{
   [self stopReading];
   [_startBtn setTitle:@"Start!" forState:UIControlStateNormal];
  }
  _isReading = !_isReading;
}
-(void)stopReading{
 [_captureSession stopRunning];
 _captureSession = nil;
 [_scanLayer removeFromSuperlayer];
 [_videoPreviewLayer removeFromSuperlayer];
}

以上内容就是本文给大家介绍ios原生二维码扫描的全部内容,希望大家喜欢。

更多精彩内容其他人还在看

objective-c中生成随机数的方法

这篇文章主要介绍了objective-c中生成随机数的方法,比较实用的功能,需要的朋友可以参考下
收藏 0 赞 0 分享

个人对于异步和多线程的关系的理解分享

异步和多线程并不是一个同等关系,异步是最终目的,多线程只是我们实现异步的一种手段。异步是当一个调用请求发送给被调用者,而调用者不用等待其结果的返回而可以做其它的事情。
收藏 0 赞 0 分享

iOS开发之路--仿网易抽屉效果

本文是IOS开发之路系列的第一篇,主要讲诉了如何仿网易新闻客户端实现抽屉效果,全部源代码都分享给大家,希望对大家有所帮助
收藏 0 赞 0 分享

iOS开发之路--微博OAuth授权_取得用户授权的accessToken

本文是IOS开发之路系列文章的第二篇,讲诉的内容是如何使用微博OAuth授权,并付源码,然后详细讲解了取得用户授权的accessToken,希望对大家有所帮助
收藏 0 赞 0 分享

iOS开发之路--微博新特性页面

本文是IOS开发之路系列的第三篇,主要是分享了微博新特性页面的制作源码,希望对大家有所帮助
收藏 0 赞 0 分享

iOS开发之路--微博骨架搭建

本文是IOS开发之路的第四篇,主要讲诉如何一步步搭建起微博的骨架,并附上源码,希望对大家的IOS开发能提供些借鉴
收藏 0 赞 0 分享

iOS开发之路--微博“更多”页面

本文是IOS开发之路系列文章第五篇,主要讲诉了,如何制作微博的更多页面,并附上效果图及源码,需要的朋友可以参考下,希望能有所帮助
收藏 0 赞 0 分享

iOS中使用schema协议调用APP和使用iframe打开APP的例子

这篇文章主要介绍了iOS中使用schema协议调用APP和使用iframe打开APP的例子,用在浏览器中打开APP,需要的朋友可以参考下
收藏 0 赞 0 分享

IOS开发之路--C语言基础知识

当前移动开发的趋势已经势不可挡,这个系列希望浅谈一下个人对IOS开发的一些见解,今天我们从最基础的C语言开始,C语言部分我将分成几个章节去说,今天我们简单看一下C的一些基础知识,更高级的内容我将放到后面的文章中。
收藏 0 赞 0 分享

IOS开发之路--C语言数组和字符串

数组在C语言中有着特殊的地位,它有很多特性,例如它的存储是连续的,数组的名称就是数组的地址等。而在C语言中是没有String类型的,那么如果要表示一个字符串,就必须使用字符串数组
收藏 0 赞 0 分享
查看更多