首先搭建一个最初步的能识别出二维码信息的最基本框架:
@interface ScanCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
AVCaptureSession * session;//输入输出的中间桥梁
}
@end
@implementation ScanCodeViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self configUI];
[self creatScanQR];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark 配置UI
- (void)configUI{
//设置导航栏标题
UILabel * titleLB = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 20)];
titleLB.font = [UIFont systemFontOfSize:18];
titleLB.textColor = [UIColor whiteColor];
titleLB.textAlignment = 1;
titleLB.text = @"二维码扫描";
self.navigationItem.titleView = titleLB;
}
#pragma mark 创建二维码扫码
- (void)creatScanQR{
//获取摄像设备
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//创建输入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
//创建输出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
session = [[AVCaptureSession alloc]init];
//高质量采集率
[session setSessionPreset:AVCaptureSessionPresetHigh];
[session addInput:input];
[session addOutput:output];
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
#pragma mark - 中间具体扫描区域
layer.frame = CGRectMake([[UIScreen mainScreen] bounds].size.width/2 - 100, UIScreen.mainScreen.bounds.size.height/2 - 100, 200, 200);
self.view.backgroundColor = [UIColor grayColor];
[self.view.layer insertSublayer:layer atIndex:0];
//开始捕获
[session startRunning];
}
#pragma mark 实现代理方法,完成二维码扫描
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if (metadataObjects.count > 0) {
[session stopRunning];
AVMetadataMachineReadableCodeObject *metaDataObject = [metadataObjects objectAtIndex:0];
//输出扫描字符串
NSLog(@"%@",metaDataObject.stringValue);
}
}
@end
这里需要注意一下,有一个坑不要踩,就是在设置outPut支持的二维码类型之前,一点要将该outPut添加到session中再对其设置,否则会一直崩溃在该句话
并出现报错:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[AVCaptureMetadataOutput setMetadataObjectTypes:] Unsupported type found - use -availableMetadataObjectTypes'
下一篇:iOS原生二维码扫描(二)