二维码扫描
- 使用ios的AVFoundation框架实现二维码扫描
- 第一步:设置相机访问权限;在Info.plist添加Privacy - Camera Usage Description权限
- 第二步:导入AVFoundation框架 #import <AVFoundation/AVFoundation.h>
- 第三步:签订AVCaptureMetadataOutputObjectsDelegate 协议
- 第四步:设置输入输出的中间桥梁
@property(nonatomic, strong)AVCaptureSession *session;/
-(void)startScanWithSize:(CGFloat)sizeValue{
AVCaptureDevice *device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
if(input){
AVCaptureMetadataOutput *output=[[AVCaptureMetadataOutput alloc]init];
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
self.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;
CGFloat xx=(self.view.bounds.size.width-sizeValue)/2;
CGFloat yy=(self.view.bounds.size.height-sizeValue)/2;
layer.frame=CGRectMake(xx, yy, sizeValue, sizeValue);
[self.view.layer insertSublayer:layer atIndex:0];
[_session startRunning];
}
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
if(metadataObjects.count>0){
[_session stopRunning];
AVMetadataMachineReadableCodeObject *metadataobject=[metadataObjects objectAtIndex:0];
NSLog(@"%@",metadataobject.stringValue);
AVCaptureVideoPreviewLayer *layer = (AVCaptureVideoPreviewLayer *)[[self.view.layer sublayers] objectAtIndex:0];
[layer removeFromSuperlayer];
}
}