您的位置:首页 > 移动开发 > IOS开发

iOS识别二维码

2016-06-22 14:24 351 查看
环境:Xcode 7.3

目的:扫描识别二维码、条形码

1、引入Foundation框架

#import <AVFoundation/AVFoundation.h>


2、设置全局变量

@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>

@property (strong,nonatomic)AVCaptureDevice * device; // 摄像头
@property (strong,nonatomic)AVCaptureDeviceInput * input; // 获取视频数据
@property (strong,nonatomic)AVCaptureMetadataOutput * output; // 输出视频数据
@property (strong,nonatomic)AVCaptureSession * session; // 拍照
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview; // 显示图像View

@end


3、初始化

// device
self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// input
self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// output
self.output = [[AVCaptureMetadataOutput alloc] init];
// 扫描窗口位置大小,即有效识别区域(原点位于屏幕右上角,x、y位置互调,width、height位置互调,即frame=(y x,height widght),默认frame=(0 0, 1 1),x、y、width、height均为百分比,0~1之间。详见底部参考1)
[self.output setRectOfInterest:CGRectMake((ckHeight - ckScanLabelWidth) / 2 / ckHeight, (ckWidth - ckScanLabelWidth) / 2 / ckWidth, ckScanLabelWidth / ckHeight, ckScanLabelWidth / ckWidth)];
// 说明:使用主线程队列,相应比较同步,使用其他队列,相应不同步,容易让用户产生不好的体验
[self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

// session
self.session = [[AVCaptureSession alloc] init];
[self.session setSessionPreset:AVCaptureSessionPresetHigh];
if ([self.session canAddInput:self.input]) {

[self.session addInput:self.input];
}

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

[self.session addOutput:self.output];
}
// 设置输出的格式
// 提示:一定要先设置会话的输出为output之后,再指定输出的元数据类型!
// AVMetadataObjectTypeQRCode:二维码
self.output.metadataObjectTypes = [NSArray arrayWithObjects:AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeQRCode, nil];

// preView
self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
self.preview.frame = self.view.bounds;
[self.view.layer insertSublayer:self.preview atIndex:0];

// start
[self.session startRunning];


4、实现代理

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

NSString * stringValue = [NSString string];
if ([metadataObjects count] >0) {

//停止扫描
[self.session stopRunning];

AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
stringValue = metadataObject.stringValue;
NSLog(@"%@",stringValue);
}
}


5、跳转应用

参考:

1、http://www.tuicool.com/articles/6jUjmur
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: