OC_扫描二维码[AVFoundation]

作者: KermitX | 来源:发表于2016-05-16 17:41 被阅读316次

    最近项目添加扫描支付宝付款二维码的功能,查看资料ZXing和ZBar,两个是推荐使用的,但是在集成Zbar的时候出现
    “Undefined symbols for architecture x86_64:”和“linker command failed with exit code 1 (use -v to see invocation)”的错误,并没有很好的解决,真是因为不兼容64位系统么?......
    所以采用的系统的AVFoundation框架实现用能。
    话不多说先上效果图


    扫描二维码

    代码来啦~~~

    成员变量
    @interface AliScanVC () <AVCaptureMetadataOutputObjectsDelegate>
    
    @property (strong, nonatomic) IBOutlet UIView *contentView;
    
    @property (strong, nonatomic) UIView * boxView;
    @property (strong, nonatomic) CALayer * scanLayer;
    
    @property (nonatomic, strong) UILabel * TipLabel;
    @property (nonatomic, strong) UIButton * inputBtn;
    @property (nonatomic, strong) UITextField * textField;
    
    @property (nonatomic, strong) AVCaptureSession * captureSession;
    @property (nonatomic, strong) AVCaptureVideoPreviewLayer * videoPreviewLayer;
    
    @end
    
    关键代码
    - (void)viewWillAppear:(BOOL)animated {
        [super viewWillAppear:animated];
        
        [self startReading];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
        [super viewWillDisappear:animated];
        
        [self stopReading];
    }
    
    #pragma mark - 二维码
    - (BOOL)startReading
    {
        // 获取 AVCaptureDevice 实例
        NSError * error;
        
        //1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
        AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        //2.用captureDevice创建输入流
        AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
        if (!input) {
            KTLog(@"captureDevice创建输入流--Error:%@", [error localizedDescription]);
            return NO;
        }
        //3.创建媒体数据输出流
        AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
        
        //4.实例化捕捉会话
        _captureSession = [[AVCaptureSession alloc] init];
        //将输入流添加到会话
        [_captureSession addInput:input];
        //将媒体输出流添加到会话中
        [_captureSession addOutput:captureMetadataOutput];
        
        //5.创建串行队列,并加媒体输出流添加到队列当中
        dispatch_queue_t dispatchQueue;
        dispatchQueue = dispatch_queue_create("myQueue", NULL);
        //设置代理
        [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
        //设置输出媒体数据类型为QRCode
        [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
        
        //6.实例化预览图层
        _videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
        
        //7.设置预览图层填充方式
        [_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        //8.设置图层的frame
        [_videoPreviewLayer setFrame:self.contentView.layer.bounds];
        
        //9.将图层添加到预览view的图层上
        [self.contentView.layer addSublayer:_videoPreviewLayer];
        
        //10.设置扫描范围
        captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
        //扫描框
        CGFloat ScanWIDTH = SCREEN_WIDTH/1.5;
        CGFloat ScanX = (SCREEN_WIDTH - ScanWIDTH)/2;
        CGFloat ScanY = (self.contentView.frame.size.height-ScanWIDTH)/3;
        _boxView = [[UIView alloc] initWithFrame:CGRectMake(ScanX,ScanY,ScanWIDTH,ScanWIDTH)];
        _boxView.layer.borderColor = [UIColor whiteColor].CGColor;
        _boxView.layer.borderWidth = 1.0f;
        [self.contentView addSubview:_boxView];
        
        // 提示
        _TipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, ScanY+ScanWIDTH+10, SCREEN_WIDTH, 18)];
        _TipLabel.text = @"请扫描客户的支付宝付款码完成收款";
        _TipLabel.textAlignment = NSTextAlignmentCenter;
        _TipLabel.textColor = [UIColor whiteColor];
        _TipLabel.font = [UIFont systemFontOfSize:14];
        [self.contentView addSubview:_TipLabel];
        
        _inputBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        _inputBtn.frame = CGRectMake(ScanX, self.contentView.frame.size.height-44-95, ScanWIDTH, 44);
        [_inputBtn setTitle:@"输入付款码" forState:UIControlStateNormal];
        _inputBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_inputBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_inputBtn setBackgroundImage:[_IMG(@"ALiBtn") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_inputBtn addTarget:self action:@selector(inputAliPayNum) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:_inputBtn];
        
        //10.开始扫描
        [_captureSession startRunning];
        
        return YES;
    }
    
    - (void)stopReading
    {
        // 停止会话
        [_captureSession stopRunning];
        _captureSession = nil;
    }
    
    #pragma mark - AVCaptureMetadataOutputObjectsDelegate
    // 获取捕获数据
    -(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
          fromConnection:(AVCaptureConnection *)connection
    {
        if (metadataObjects != nil && [metadataObjects count] > 0) {
            
            AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
            NSString *result;
            if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
                result = metadataObj.stringValue;
                [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:result waitUntilDone:NO];
                
            } else {
                KTLog(@"不是二维码");
                [_captureSession startRunning];
            }
            
            
        }
        
    }
    
    // 处理结果
    - (void)reportScanResult:(NSString *)result
    {
        [self stopReading];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"二维码扫描结果"
                                                            message:result
                                                           delegate:nil
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles: nil];
        
        [alert show];
    }
    
    并没有用到的闪光灯功能,并没有人会在关着灯的情况下进行扫描操作🐷
    - (void)systemLightSwitch:(BOOL)open
    {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch]) {
            [device lockForConfiguration:nil];
            if (open) {
                [device setTorchMode:AVCaptureTorchModeOn];
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
            }
            [device unlockForConfiguration];
        }
    }
    

    相关文章

      网友评论

        本文标题:OC_扫描二维码[AVFoundation]

        本文链接:https://www.haomeiwen.com/subject/zzvbrttx.html