之前总觉得二维码扫描很高大上,其实apple工程师早就为我们提供了便捷的方法。二维码扫描第三方的库也挺多的,不过效率高的当属系统提供的扫描方法。
二维码扫描主要用到了以下几个类:
AVCaptureDevice
,AVCaptureDeviceInput
,AVCaptureMetadataOutput
,AVCaptureSession
,AVCaptureVideoPreviewLayer
它们之间的关系看这篇文章
扫描的核心代码如下:(最后附上完整代码)
//获取摄像设备
AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
if (!device) return;
//创建输入流
AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if (!input) return;
//创建输出流
AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
if (!output) return;
output.rectOfInterest = CGRectMake(0.1, 0, 0.9, 1);
//设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//初始化链接对象
_session = [[AVCaptureSession alloc]init];
//高质量采集率
[_session setSessionPreset:AVCaptureSessionPresetHigh];
if ([_session canAddInput:input]) {
[_session addInput:input];
}else{
return;
}
if ([_session canAddOutput:output]) {
[_session addOutput:output];
}else{
return;
}
//设置扫码支持的编码格式(如下设置条形码和二维码兼容)
output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
layer.frame = self.view.layer.bounds;
[self.view.layer insertSublayer:layer atIndex:0];
//开始捕获
[_session startRunning];
完整代码地址