扫描二维码

本文介绍了一个简单的iOS应用程序,用于实现二维码扫描功能。该应用利用AVFoundation框架创建视频捕捉会话并解析摄像头捕获的二维码数据。
//
//  ViewController.m
//  SaoMiaoErWeiMa
//
//  Created by hq on 16/5/16.
//  Copyright  2016年 hanqing. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController () <AVCaptureMetadataOutputObjectsDelegate>

@property(nonatomic,weak) AVCaptureSession *session;

@property(nonatomic,weak) AVCaptureVideoPreviewLayer *layer;

- (IBAction)scan;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}


//扫描二维码
- (IBAction)scan {
   
   
    //创建捕捉会话
    AVCaptureSession *session=[[AVCaptureSession alloc]init];
    
    self.session=session;
    
    //添加输入设备
    AVCaptureDevice *device=[AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *input=[AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    [session addInput:input];
    
    
    
    //添加输出数据
    AVCaptureMetadataOutput *output=[[AVCaptureMetadataOutput alloc]init];
    
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    [session addOutput:output];
    
    //输出到是二维码数据,必须写在添加之后
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    //添加扫描图层
    AVCaptureVideoPreviewLayer *layer=[AVCaptureVideoPreviewLayer layerWithSession:session];
    
    layer.frame=CGRectMake(0, 0, 300, 300);
    
    [self.view.layer addSublayer:layer];
    
    self.layer=layer;
    
    //开始扫描
    [session startRunning];
    
}

//通过代理获得扫描的数据
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    
    if (metadataObjects.count>0) {
        
        NSLog(@"扫描到数据");
        
        //获取扫描到的数据
        AVMetadataMachineReadableCodeObject *obj=[metadataObjects lastObject];
        
        //停止扫描
        [self.session stopRunning];
        
        //移除我们的layer
        [self.layer removeFromSuperlayer];
        
    }
    else{
        
        NSLog(@"没有扫描到数据");
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}
@end













评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值