//
// Copyright 2016年 hjl. All rights reserved.
//
#import "HHQrcodeController.h"
#import <AVFoundation/AVFoundation.h>
@interface HHQrcodeViewController () <AVCaptureMetadataOutputObjectsDelegate>
/** 会话 */
@property (nonatomic, strong) AVCaptureSession *session;
//* 预览图层 */
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *previewLayer;
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection;
@end
@implementation HHQrcodeViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1. 实例化拍摄设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 2. 设置输入设备
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
// 3. 实例化拍摄元数据输出
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 4. 设置输出数据代理
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// 5. 添加拍摄会话
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 6. 添加会话输入/输出
if ([session canAddInput:input]) {
[session addInput:input];
}
if ([session canAddOutput:output]) {
[session addOutput:output];
}
//7 设置输出数据类型,需要将元数据输出添加到会话后,才能指定元数据类型,否则会报错
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
//8 实例化预览图层
AVCaptureVideoPreviewLayer *previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
previewLayer.frame = self.view.bounds;
self.previewLayer = previewLayer;
//9 将图层插入当前视图
[self.view.layer insertSublayer:previewLayer atIndex:0];
//10 启动会话
[_session startRunning];
}
#pragma 代理
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
//1 判断是否获取到数据
if (metadataObjects.count > 0) {
//2 停止刷新
[self.session stopRunning];
//3 移除预览图层
[self.previewLayer removeFromSuperlayer];
//4 读取数据
AVMetadataMachineReadableCodeObject *obj = [metadataObjects lastObject];
HHLog(@"%@", obj.stringValue);
}
}
@end
时间: 2024-11-26 06:36:04