iOS---扫码(二维码/条形码)

我在两个项目中分别使用了ZBarSDK与系统自带的扫码,今天主要介绍一下系统自带的扫码(AVCaptureSession),需导入 

#import <AVFoundation/AVFoundation.h>

1。系统自带的 

   (1)先声明两个属性                 

              @property (nonatomic,strong)AVCaptureSession *session; //捕捉会话

              @property (nonatomic,strong)AVCaptureVideoPreviewLayer *layer; //扫描图层

   (2)添加输入设备并检查设备是否支持相机    

            //添加输入设备并创建捕捉会话        

                AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

                self.session = [[AVCaptureSession alloc] init];

                AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];

                NSError *error=nil;

                if (input) {

                     [self.session addInput:input];

                }else{

                    NSLog(@"获取摄像设备error:%@",[error localizedDescription]);

                }

          //检查相机状态

               AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]; 

               if(status == AVAuthorizationStatusAuthorized) {       

                    [self setupCamera];   

               } else {

                    [self showStr:@"您没有权限访问相机" withSelf:self withMinier:2.0];

              }

    (3)在能打开相机的情况下创扫描图层         

          //添加输出数据

               AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];

               [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

         //高质量采集率

              [self.session setSessionPreset:AVCaptureSessionPresetHigh];

              [self.session addOutput:output];

        //设置扫码支持的编码格式(如下设置条形码和二维码兼容)

             [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];    

        //添加扫描图层

            self.layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];

            self.layer.frame = CGRectMake((ScreenWidth-250)/2,ScreenHeight*0.25, 250, 250);

            self.layer.videoGravity = AVLayerVideoGravityResizeAspectFill;

            [self.view.layer addSublayer:self.layer];

    (4)开始扫描

            [self.session startRunning];

     (5)如果扫描到数据会调用代理方法 (遵守AVCaptureMetadataOutputObjectsDelegate协议)       

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

     注意:xcode8的 用户在使用这个功能的时候要先再plist。info 中添加项: Privacy - Camera Usage Description     是否允许此App使用你的相机?

2.ZBarSDK

    参考自:http://www.mincoder.com/article/4419.shtml

            

posted @ 2016-12-01 14:48  青语  阅读(571)  评论(0编辑  收藏  举报