1. 程式人生 > >iOS二維碼掃描

iOS二維碼掃描

ont 代碼 畫面 告訴 nds ima dds rst bounds

每一步:添加 AVFoundation.framework 庫

General > Linked Frameworks and Libraries

技術分享

第二步:代碼集成

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>

//1. 有個素材

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>

/** 2.輸入設置 采集攝像頭捕捉到的信息 */

@property (nonatomic, strong) AVCaptureDeviceInput *input;

/** 3.輸出設備 解析輸入設備采集到的信息 */

@property (nonatomic, strong) AVCaptureMetadataOutput *output;

/** 4. layer (特殊圖層 能夠展示攝像頭采集到的畫面) 展示輸入設備采集到的信息 */

@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;

/** 5.關聯輸入設備和輸出設備 會話 */

@property (nonatomic, strong) AVCaptureSession *session;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

}

// 點擊掃描二維碼

- (IBAction)click:(id)sender {

// 1.創建輸入設備

// AVMediaTypeVideo 攝像頭

// AVMediaTypeAudio 麥克風

// AVCaptureDeviceInput 輸入設備 default默認後置

// AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

NSArray *allDevice = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];

self.input = [AVCaptureDeviceInput deviceInputWithDevice:[allDevice firstObject] error:nil];

//2. 創建輸出設備

self.output = [[AVCaptureMetadataOutput alloc]init];

//解析 返回的數據

//設置輸出設備的代理 返回解析後的數據

[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

//3.創建會話

self.session = [[AVCaptureSession alloc]init];

//4.關聯 會話和設備

if ([self.session canAddInput:self.input]) {

[self.session addInput:self.input];

}

if ([self.session canAddOutput:self.output]) {

[self.session addOutput:self.output];

}

//告訴數據類型 AVMetadataObjectTypeQRCode 二維碼

self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];

// 掃描框大小 整個屏幕

[self.session setSessionPreset:AVCaptureSessionPreset640x480];

//5.指定layer 的 frame 然後添加到 view上

self.layer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];

self.layer.frame = self.view.bounds;

[self.view.layer addSublayer:self.layer];

//開啟會話

[self.session startRunning];

}

//掃描出結果後就會調用的方法

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

AVMetadataMachineReadableCodeObject *objc = [metadataObjects firstObject];

NSString *str = objc.stringValue;

NSLog(@"%@",str);

//停止掃描

[self.session stopRunning];

//移除 layer

[self.layer removeFromSuperlayer];

}

@end

iOS二維碼掃描