二维码(QRCode)的本质其实就是一个字符串,我们的最终目的就是将二维码图片转换成字符串.
首先导入AVFoundation框架
#import <AVFoundation/AVFoundation.h>
实例化有关二维码扫描的四个对象
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
//输入设备 也就是摄像头
@property(nonatomic, strong)AVCaptureDeviceInput *input;
//输出的元数据
@property(nonatomic, strong)AVCaptureMetadataOutput *output;
//展示图层
@property(nonatomic, strong)AVCaptureVideoPreviewLayer *preLayer;
//会话(输入设备、输出的元数据和展示图层都需要与会话相关联)
@property(nonatomic, strong)AVCaptureSession *session;
@end
将输入设备、输出设备、展示图层与会话关联起来
AVCaptureDeviceDiscoverySession *discoverySession = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera] mediaType:AVMediaTypeVideo position:AVCaptureDevicePositionBack];
//获取设备 也就是摄像头 这里只获取后置摄像头
NSArray *devices = discoverySession.devices;
self.input = [[AVCaptureDeviceInput alloc]initWithDevice:[devices firstObject] error:nil];
self.output = [[AVCaptureMetadataOutput alloc]init];
self.session = [[AVCaptureSession alloc]init];
//将输入设备与会话关联
if ([self.session canAddInput:self.input]) {
[self.session addInput:self.input];
}
//将输出设备与会话关联
if ([self.session canAddOutput:self.output]) {
[self.session addOutput:self.output];
}
//设置输出设备的代理
[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// NSLog(@"%@",[self.output availableMetadataObjectTypes]);
//输出元数据类型为二维码
self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
//将展示图层与会话关联
self.preLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
self.preLayer.frame = self.view.bounds;
[self.view.layer addSublayer:self.preLayer];
[self.session setSessionPreset:AVCaptureSessionPreset1920x1080];
[self.session startRunning];
输出设备代理方法
//解析完毕会调用这个方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
AVMetadataMachineReadableCodeObject *objc = [metadataObjects firstObject];
//输出扫描结果
NSLog(@"%@",objc.stringValue);
[self.preLayer removeFromSuperlayer];
[self.session stopRunning];
//后续对扫描出来的字符串进一步进行操作
}
输出的字符串