IOS-二維碼掃描

來源:互聯網
上載者:User

標籤:

如今二維碼隨處可見,無論是實物商品還是各種禮券都少不了二維碼的身影。而手機等行動裝置又成為二維碼的一個很好的應用平台,在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-二維碼掃描

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.