標籤:
如今二維碼隨處可見,無論是實物商品還是各種禮券都少不了二維碼的身影。而手機等行動裝置又成為二維碼的一個很好的應用平台,在ios7之前我們基本上都是使用《ZBarSDK》這個第三方類,但是在ios7之後系統的AVMetadataObject 為我們提供瞭解析二維碼的介面,因為自己對這一塊的研究不深刻,經過尋找資料發現使用原生API掃描和處理的效率遠遠高於第三方庫,所以在這裡簡單介紹一下官方原聲API二維碼和條碼的掃描
看看下面代碼:
首先引進標頭檔,設定好代理
#import "LBViewController.h"#import <AVFoundation/AVFoundation.h>@interface LBViewController ()<AVCaptureMetadataOutputObjectsDelegate>//設定代理用於處理映像掃描後的資訊{ AVCaptureSession *session;//掃描輸入輸出中間橋樑}
- (void)viewDidLoad{ [super viewDidLoad]; //擷取攝像裝置 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; //建立輸入對象 AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; //建立輸出對象 AVCaptureMetadataOutput *outDevice = [[AVCaptureMetadataOutput alloc] init]; //這裡是對我們看到的掃描範圍進行一個限定(下面的數字 表示的是介面的下半部分)(x,y,w,h)都是針對左上方的點來進行判斷的 outDevice.rectOfInterest = CGRectMake(0.5, 0, 0.5, 1); //設定代理 在主線程裡重新整理 [outDevice setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; //初始化連結化物件 session = [[AVCaptureSession alloc] init]; //設定採集資料的品質 [session setSessionPreset:AVCaptureSessionPresetHigh];//高品質 [session addInputWithNoConnections:inputDevice]; [session addOutputWithNoConnections:outDevice]; //設定掃碼支援的編碼格式(如下:設定條碼和二維碼相容) outDevice.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code]; AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session]; layer.videoGravity = AVLayerVideoGravityResizeAspectFill; layer.frame = self.view.layer.bounds; [self.view.layer insertSublayer:layer atIndex:0]; //開始捕獲資料 [session startRunning];}
//下面就是對代理回調
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{ if (metadataObjects.count > 0) { AVMetadataMachineReadableCodeObject *metadaobject = [metadataObjects objectAtIndex:0]; //輸出掃描出來的字串 NSLog(@"%@",metadaobject.stringValue); } }
申明:我只是個初學者,如有問題,歡迎朋友們指正,共同探討。謝謝!
IOS-二維碼掃描