iOS开发--二维码的扫描
Posted Chaos_G
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS开发--二维码的扫描相关的知识,希望对你有一定的参考价值。
一.需要包含头文件
#import <AVFoundation/AVFoundation.h>
二.通过设置<AVCaptureMetadataOutputObjectsDelegate>代理可以监听扫描到的二维码中的信息
三.具体代码
1 #import "ViewController.h" 2 #import <AVFoundation/AVFoundation.h> 3 4 @interface ViewController () <AVCaptureMetadataOutputObjectsDelegate> 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad { 11 [super viewDidLoad]; 12 } 13 14 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 15 { 16 // 1.创建捕捉会话 17 AVCaptureSession *session = [[AVCaptureSession alloc] init]; 18 19 // 2.设置输入设备 20 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 21 AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil]; 22 [session addInput:inputDevice]; 23 24 // 3.设置输入方式 25 AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init]; 26 [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; 27 [session addOutput:output]; 28 [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]]; 29 30 // 4.添加一个显示的layer 31 AVCaptureVideoPreviewLayer *layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session]; 32 layer.frame = self.view.bounds; 33 [self.view.layer addSublayer:layer]; 34 35 // 5.开始扫描 36 [session startRunning]; 37 } 38 39 #pragma mark - 获取扫描结果 40 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection 41 { 42 if (metadataObjects.count > 0) { 43 AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject]; 44 NSLog(@"%@", object.stringValue); 45 } 46 } 47 48 @end
以上是关于iOS开发--二维码的扫描的主要内容,如果未能解决你的问题,请参考以下文章