首页 > 代码库 > iOS二维码扫描

iOS二维码扫描

测试环境:iPhone 5s  iOS7.1

首先添加框架AVFoundation.framework,然后导入自定义类CMCaptureViewController.h、CMCaptureViewController.m,以及用到的图片资源:line@2x.png、pick_bg@2x.png。

用的时候只需要切换到二维码视图控制器CMCaptureViewController即可,会跳到二维码扫描界面

如:

1 [self presentViewController:captureViewController animated:YES completion:nil];

要获得扫描的二维码内容,只需要成为 其委托,实现委托方法

1 - (void)captureController:(CMCaptureViewController *)controller data:(id)metadata;

参数metadata中包含扫描到的字符串。

CMCaptureViewController.h、CMCaptureViewController.m的源代码如下:

 1 //  CMCaptureViewController.h 2 //  二维码扫描 3  4 #import <UIKit/UIKit.h> 5 #import <AVFoundation/AVFoundation.h> 6  7 @class CMCaptureViewController; 8 @protocol CMCaptureViewDelegate <NSObject> 9 10 - (void)captureController:(CMCaptureViewController *)controller data:(id)metadata;11 12 @end13 14 @interface CMCaptureViewController : UIViewController<AVCaptureMetadataOutputObjectsDelegate>15 {16     int num;17     BOOL upOrdown;18     NSTimer * timer;19 }20 @property (strong,nonatomic)AVCaptureDevice * device;21 @property (strong,nonatomic)AVCaptureDeviceInput * input;22 @property (strong,nonatomic)AVCaptureMetadataOutput * output;23 @property (strong,nonatomic)AVCaptureSession * session;24 @property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;25 @property (nonatomic, retain) UIImageView * line;26 @property (nonatomic, weak) id <CMCaptureViewDelegate> delegate;27 28 @end

 

  1 //  CMCaptureViewController.m  2 //  二维码扫描  3   4   5 #import "CMCaptureViewController.h"  6   7 @interface CMCaptureViewController ()  8   9 @end 10  11 @implementation CMCaptureViewController 12  13 - (void)loadView 14 { 15     [super loadView]; 16     self.view.backgroundColor = [UIColor redColor]; 17     UIButton * scanButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 18     [scanButton setTitle:@"取消" forState:UIControlStateNormal]; 19     scanButton.frame = CGRectMake(100, 420, 120, 40); 20     [scanButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside]; 21     [self.view addSubview:scanButton]; 22      23     UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(15, 40, 290, 50)]; 24     labIntroudction.backgroundColor = [UIColor clearColor]; 25     labIntroudction.numberOfLines=2; 26     labIntroudction.textColor=[UIColor whiteColor]; 27     labIntroudction.text=@"将二维码图像置于矩形方框内,离手机摄像头10CM左右,系统会自动识别。"; 28     [self.view addSubview:labIntroudction]; 29      30      31     UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 100, 300, 300)]; 32     imageView.image = [UIImage imageNamed:@"pick_bg"]; 33     [self.view addSubview:imageView]; 34      35     upOrdown = NO; 36     num =0; 37     _line = [[UIImageView alloc] initWithFrame:CGRectMake(50, 110, 220, 2)]; 38     _line.image = [UIImage imageNamed:@"line.png"]; 39     [self.view addSubview:_line]; 40      41     timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES]; 42  43 } 44  45  46 -(void)animation1 47 { 48     if (upOrdown == NO) { 49         num ++; 50         _line.frame = CGRectMake(50, 110+2*num, 220, 2); 51         if (2*num == 280) { 52             upOrdown = YES; 53         } 54     } 55     else { 56         num --; 57         _line.frame = CGRectMake(50, 110+2*num, 220, 2); 58         if (num == 0) { 59             upOrdown = NO; 60         } 61     } 62  63 } 64  65 -(void)backAction 66 { 67      68     [self dismissViewControllerAnimated:YES completion:^{ 69         [timer invalidate]; 70     }]; 71 } 72  73  74  75 -(void)viewWillAppear:(BOOL)animated 76 { 77     [self setupCamera]; 78 } 79 - (void)setupCamera 80 { 81     // Device 82     _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo]; 83  84     // Input 85     _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil]; 86      87     // Output 88     _output = [[AVCaptureMetadataOutput alloc]init]; 89     [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; 90      91     // Session 92     _session = [[AVCaptureSession alloc]init]; 93     [_session setSessionPreset:AVCaptureSessionPresetHigh]; 94     if ([_session canAddInput:self.input]) 95     { 96         [_session addInput:self.input]; 97     } 98      99     if ([_session canAddOutput:self.output])100     {101         [_session addOutput:self.output];102     }103     104     // 条码类型 AVMetadataObjectTypeQRCode105     _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];106     107     // Preview108     _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];109     _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;110     _preview.frame =CGRectMake(20,110,280,280);111     [self.view.layer insertSublayer:self.preview atIndex:0];112     113     // Start114     [_session startRunning];115 }116 #pragma mark AVCaptureMetadataOutputObjectsDelegate117 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection118 {119    120     NSString *stringValue;121     122     if ([metadataObjects count] >0)123     {124         AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];125         stringValue =http://www.mamicode.com/ metadataObject.stringValue;126         NSLog(@"[%@]", stringValue);127     }128     129     [_session stopRunning];130 131     [self dismissViewControllerAnimated:YES completion:^132     {133         [timer invalidate];134         135         dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{136             if ([self.delegate respondsToSelector:@selector(captureController:data:)])137             {138                 [self.delegate captureController:self data:stringValue];139             }140         });141 142     }];143 }144 145 - (void)didReceiveMemoryWarning146 {147     [super didReceiveMemoryWarning];148     // Dispose of any resources that can be recreated.149 }150 151 152 153 @end

pick_bg@2x.png

line@2x.png

iOS二维码扫描