//1.创建捕捉会话
AVCaptureSession *session = [[AVCaptureSession alloc]init];
self.session = session;
//2. 添加输入设备
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
AVCaptureDeviceInput *dinput = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:dinput];
// 3. 添加输出设备
AVCaptureMetadataOutput *metadataOutput = [[AVCaptureMetadataOutput alloc ]init];
//3.1这里实在主线程中设置的代理来获取结果实际上要做实际的考虑
[metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:metadataOutput];
//3.2 添加到seesion 后才能添加输出的类型
[metadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
//4.添加输出图层
AVCaptureVideoPreviewLayer *preiewLayer =[AVCaptureVideoPreviewLayer layerWithSession:session];
preiewLayer.frame =self.view.bounds;
self.layer = preiewLayer;
[self.view.layer addSublayer:preiewLayer];
// 5开始扫描
[session startRunning];
pragma marke 扫描的代理方法 实现这个代理方法,在这里面获取扫描的结果
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if(metadataObjects.count >0){
NSLog(@"扫描到二维码");
// 获取扫描结果
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@",object.stringValue);
// 停止扫描
[self.session stopRunning];
[self.layer removeFromSuperlayer];
}else{
NSLog(@"没有扫描到数据");
}
}