前面学习了二维码的生成,今天简单介绍下如何读取二维码。
注意:要成功读取二维码,一定要有真机才能测试,模拟器不行
步骤
- 导入AVFoundation框架
- 利用摄像头(真机)识别二维码
- 输入(摄像头)
- 由会话将摄像头采集到的二维码图像转换成字符串数据
- 输出(数据)
- 由预览图层显示扫描场景
代码实现
导入框架
#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];
}
}
成功读取二维码
网友评论