iOS使用系統API進行二維碼條形碼掃描遇到的坑

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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容