//須要真機 #import "ViewController.h" #import <AVFoundation/AVFoundation.h> @interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>//用於處理採集信息的代理 { AVCaptureSession * session;//輸入輸出的中間橋樑 } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //獲取攝像設備 AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; //建立輸入流 AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; //建立輸出流 AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init]; //設置代理 在主線程裏刷新 [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; //初始化連接對象 session = [[AVCaptureSession alloc]init]; //高質量採集率 [session setSessionPreset:AVCaptureSessionPresetHigh]; // 一、這個CGRect參數和普通的Rect範圍不太同樣,它的四個值的範圍都是0-1,表示比例。 // 二、通過測試發現,這個參數裏面的x對應的偏偏是距離左上角的垂直距離,y對應的是距離左上角的水平距離。 // 三、寬度和高度設置的狀況也是相似。 // 三、舉個例子若是咱們想讓掃描的處理區域是屏幕的下半部分,咱們這樣設置 // output.rectOfInterest=CGRectMake(0.5,0,0.5, 1); [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]; } #pragma mark 信息捕獲代理方法 -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{ if (metadataObjects.count>0) { //[session stopRunning]; AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ]; //輸出掃描字符串 NSLog(@"%@",metadataObject.stringValue); } } @end