iOS實現一個簡單的掃碼功能

用到的是AVFoundationsession

須要用到Capture,Input,Output,Session,previewLayer相關類ide

#import "ScanQRCodeController.h"
#import <AVFoundation/AVFoundation.h>
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface ScanQRCodeController ()<AVCaptureMetadataOutputObjectsDelegate> @property (nonatomic,strong)AVCaptureSession *session; @property (nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer; @end

@implementation ScanQRCodeController - (void)viewDidLoad { [super viewDidLoad]; _session = [[AVCaptureSession alloc]init]; AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; NSError *error = nil; AVCaptureDeviceInput *input = [[AVCaptureDeviceInput alloc]initWithDevice:device error:&error]; if (error) { NSLog(@"初始化input失敗,%@",error); return; } if ([_session canAddInput:input]) { [_session addInput:input]; NSLog(@"添加input成功"); }else{ NSLog(@"添加input失敗"); return; } AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init]; if ([_session canAddOutput:output]) { [_session addOutput:output]; NSLog(@"添加output成功"); }else{ NSLog(@"添加output失敗"); return; } [output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,nil]]; dispatch_queue_t dispatchQueue = dispatch_queue_create("myQueue", NULL); [output setMetadataObjectsDelegate:self queue:dispatchQueue]; _previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:_session]; [_previewLayer setFrame:self.view.layer.bounds]; [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill]; [self.view.layer insertSublayer:_previewLayer atIndex:0]; //10.設置掃描範圍 // output.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.6f, 0.6f); //10.開始掃描
 [_session startRunning]; NSLog(@"開始掃描"); } - (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection{ NSLog(@"come:%@",metadataObjects); } @end

注意:atom

1.輸出類型錯誤的話,沒有輸出spa

掃描條形碼rest

[output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,nil]];

掃描二維碼code

[output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode,nil]];

2.設置output的類型必須在執行addOutput方法以後,不然會崩潰blog

相關文章
相關標籤/搜索