您现在的位置是:首页 > 文章详情

iOS QRCode(二维码)

日期:2018-01-21点击:452

实现思路

  1. 输入设备(用来获取外界信息) 摄像头, 麦克风, 键盘
  2. 输出设备 (将收集到的信息, 做解析, 来获取收到的内容)
  3. 会话session (用来连接输入和输出设备)
  4. 特殊的layer (展示输入设备所采集的信息)

1. 导包

#import <AVFoundation/AVFoundation.h> 

2. 代码

#import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate> //1. 输入设备(用来获取外界信息) 摄像头, 麦克风, 键盘 @property (nonatomic, strong) AVCaptureDeviceInput *input; //2. 输出设备 (将收集到的信息, 做解析, 来获取收到的内容) @property (nonatomic, strong) AVCaptureMetadataOutput *output; //3. 会话session (用来连接输入和输出设备) @property (nonatomic, strong) AVCaptureSession *session; //4. 特殊的layer (展示输入设备所采集的信息) @property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; @end @implementation ViewController #pragma mark 点击屏幕开始扫描 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { //1.输入设备(用来获取外界信息) 摄像头, 麦克风, 键盘 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; self.input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; //2.输出设备 (将收集到的信息, 做解析, 来获取收到的内容) self.output = [AVCaptureMetadataOutput new]; //3.会话session (用来连接输入和输出设备) self.session = [AVCaptureSession new]; // 会话扫描展示的大小 [self.session setSessionPreset:AVCaptureSessionPresetHigh]; // 会话跟输入和输出设备关联 if ([self.session canAddInput:self.input]) { [self.session addInput:self.input]; } if ([self.session canAddOutput:self.output]) { [self.session addOutput:self.output]; } //下面两句代码应该写在此处 //制定输出设备的代理, 用来接受返回的数据 [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; //设置元数据类型 二维码QRCode [self.output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; //4.特殊的layer (展示输入设备所采集的信息) self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session]; // 大小layer的大小 self.previewLayer.frame = self.view.bounds; [self.view.layer addSublayer:self.previewLayer]; //5. 启动会话 [self.session startRunning]; } /** captureOutput : 输出设备 metadataObjects : 元数据对象的数组 connection : 连接 */ - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { //1. 停止会话 [self.session stopRunning]; //2. 删除layer [self.previewLayer removeFromSuperlayer]; //3. 遍历数据获取内容 for (AVMetadataMachineReadableCodeObject *obj in metadataObjects) { NSLog(@"obj: %@",obj.stringValue); } } @end 
原文链接:https://yq.aliyun.com/articles/663423
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章