iOS QRCode(二维码)

实现思路

  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



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值