IOS-二维码扫描

如今二维码随处可见,无论是实物商品还是各种礼券都少不了二维码的身影。而手机等移动设备又成为二维码的一个很好的应用平台,在ios7之前我们基本上都是使用《ZBarSDK》这个第三方类,但是在ios7之后系统的AVMetadataObject 为我们提供了解析二维码的接口,因为自己对这一块的研究不深刻,经过查找资料发现使用原生API扫描和处理的效率远远高于第三方库,所以在这里简单介绍一下官方原声API二维码和条形码的扫描

看看下面代码:

首先引进头文件,设置好代理

#import "LBViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface LBViewController ()<AVCaptureMetadataOutputObjectsDelegate>//设置代理用于处理图像扫描后的信息

{
    AVCaptureSession *session;//扫描输入输出中间桥梁
}
- (void)viewDidLoad
{
    [super viewDidLoad];
     //获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //创建输入对象
    AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    //创建输出对象
    AVCaptureMetadataOutput *outDevice = [[AVCaptureMetadataOutput alloc] init];
    
    //这里是对我们看到的扫描范围进行一个限定(下面的数字 表示的是界面的下半部分)(x,y,w,h)都是针对左上角的点来进行判断的
    outDevice.rectOfInterest = CGRectMake(0.5, 0, 0.5, 1);
    
    //设置代理 在主线程里刷新
    [outDevice setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    session = [[AVCaptureSession alloc] init];
    
    //设置采集数据的质量
    [session setSessionPreset:AVCaptureSessionPresetHigh];//高质量
    
    [session addInputWithNoConnections:inputDevice];
    [session addOutputWithNoConnections:outDevice];
    
    //设置扫码支持的编码格式(如下:设置条形码和二维码兼容)
    outDevice.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code];
    
    AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    layer.frame = self.view.layer.bounds;
    
    [self.view.layer insertSublayer:layer atIndex:0];
    
    //开始捕获数据
    [session startRunning];
}

//下面就是对代理回调

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0)
    {
        AVMetadataMachineReadableCodeObject *metadaobject = [metadataObjects objectAtIndex:0];
        
        //输出扫描出来的字符串
        NSLog(@"%@",metadaobject.stringValue);
    }
    
}

 申明:我只是个初学者,如有问题,欢迎朋友们指正,共同探讨。谢谢!

 
 
 
posted @ 2015-09-14 14:36  逐梦boys  阅读(381)  评论(0编辑  收藏  举报