实用技术第2篇——如何生成和读取二维码【下】

2015-09-17  本文已影响204人  海强_hq
前面学习了二维码的生成,今天简单介绍下如何读取二维码。
注意:要成功读取二维码,一定要有真机才能测试,模拟器不行

步骤

代码实现

导入框架
#import <AVFoundation/AVFoundation.h>
// 遵守协议
@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate> 
/** 捕捉会话 */
@property (nonatomic, weak) AVCaptureSession *session;

/** 预览图层 */
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
    // 1.创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2.设置输入设备(摄像头)
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3.设置输出数据(元数据)
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 4.添加阅览图层
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer      layerWithSession:session];
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
    // 5.开始扫描
    [session startRunning];
实现AVCaptureMetadataOutput的代理方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        // 1.获取元数据
        AVMetadataMachineReadableCodeObject *metadata = [metadataObjects lastObject];
        
        // 2.获取具体的值
        NSLog(@"%@", metadata.stringValue);
        
        // 3.停止扫描
        [self.session stopRunning];
        
        // 4.将预览图层移除
        [self.layer removeFromSuperlayer];
    }
}

成功读取二维码

上一篇下一篇

猜你喜欢

热点阅读