作品链接:
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];
}
}