美文网首页
iOS使用系统API进行二维码条形码扫描遇到的坑

iOS使用系统API进行二维码条形码扫描遇到的坑

作者: 小怪之屋 | 来源:发表于2016-04-06 16:48 被阅读3436次

1、扫描二维码可以,扫描条形码一直没有反应
2、demo只集成条形码,则没有这个问题

---

>

Step1:需要导入:AVFoundation Framework 包含头文件:

#import

Step2:设置捕获会话

设置 AVCaptureSession 和 AVCaptureVideoPreviewLayer 成员

[即,创建会话和输出对象]

Step3:创建会话,读取输入流

```Objective-C

- (void)beginScanning

{

//获取摄像设备

AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

//创建输入流

AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

if (!input) return;

//创建输出流

AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];

//设置代理 在主线程里刷新

[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

//设置有效扫描区域

CGRect scanCrop=[self getScanCrop:_scanWindow.bounds readerViewBounds:self.view.frame];

output.rectOfInterest = scanCrop;

__weak typeof(self) weakSelf = self;

[[NSNotificationCenter defaultCenter]addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {

if (weakSelf){

//调整扫描区域

AVCaptureMetadataOutput *output = weakSelf.session.outputs.firstObject;

output.rectOfInterest = scanCrop;

}

}];

//初始化链接对象

_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;

layer.frame=self.view.layer.bounds;

[self.view.layer insertSublayer:layer atIndex:0];

//开始捕获

[_session startRunning];

}

Step4:停止读取

-(void)stopReading

{

// 停止会话

[_captureSessionstopRunning];

_captureSession=nil;

}

Step5:代理中获取捕获数据,并处理

-(void)captureOutput:(AVCaptureOutput*)captureOutputdidOutputMetadataObjects:(NSArray*)metadataObjectsfromConnection:(AVCaptureConnection*)connection

{

if(metadataObjects!=nil&&[metadataObjectscount]>0)

{

AVMetadataMachineReadableCodeObject* metadataObj =[metadataObjectsobjectAtIndex:0];

NSString*result;

if([[metadataObjtype]isEqualToString:AVMetadataObjectTypeQRCode])

{

result=metadataObj.stringValue;

}

else

{

NSLog(@"不是二维码");

}[selfperformSelectorOnMainThread:@selector(reportScanResult:)withObject:resultwaitUntilDone:NO];

}

}

```

---

以上基本就是二维码的获取流程,和扫一扫二维码伴随的就是开启系统照明,这个比较简单,也是利用AVCaptureDevice,请看如下实现:

参考链接:
http://my.oschina.net/jeans/blog/519365
http://www.cnblogs.com/lzjsky/p/5057134.html

相关文章

网友评论

      本文标题:iOS使用系统API进行二维码条形码扫描遇到的坑

      本文链接:https://www.haomeiwen.com/subject/dilmlttx.html