码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发--二维码的扫描

时间:2016-06-14 22:07:42      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:

一.需要包含头文件

#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开发--二维码的扫描

标签:

原文地址:http://www.cnblogs.com/gchlcc/p/5585513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!