OC中扫描二维码代码实现

作者: 打电话记错号码的人 | 来源:发表于2016-09-09 22:48 被阅读470次

作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles
1.实现扫描方法

AVCaptureSession集成在<AVFoundation/AVFoundation.h>
@property (nonatomic, weak) AVCaptureSession *session;
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;

  // 1.创建捕捉会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    self.session = session;
    
    // 2.设置输入(摄像头)
    //  AVMediaTypeVideo:摄像头 AVMediaTypeAudio:话筒 AVMediaTypeMuxed:弹幕
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    [session addInput:input];
    
    // 3.设置输出(数据) 需遵守AVCaptureMetadataOutputObjectsDelegate代理
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    [session addOutput:output];
    // 设置输入的类型,必须在output加入到会话之后来设置
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    // 4.添加阅览图层
    AVCaptureVideoPreviewLayer *layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
    layer.frame = self.view.bounds;
    [self.view.layer addSublayer:layer];
    self.layer = layer;
    
    // 5.开始扫描
    [session startRunning];

2.实现元数据的回调方法

#pragma mark - AVCaptureMetadataOutputObjectsDelegate方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        // 1.获取扫描到的内容
        AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
        NSLog(@"%@", object.stringValue);
        
        // 2.停止会话
        [self.session stopRunning];
        
        // 3.移除预览图层
        [self.layer removeFromSuperlayer];
    }
}

相关文章

网友评论

    本文标题:OC中扫描二维码代码实现

    本文链接:https://www.haomeiwen.com/subject/gncyettx.html