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

猫猫学iOS之二维码学习,快速打开相机读取二维码

2015-09-25 13:33 525 查看
猫猫分享,必须精品

原创文章,欢迎转载。转载请注明:翟乃玉的博客

地址:http://blog.csdn.net/u013357243

上一篇文章写了怎么生成二维码,这儿就说说怎么读取吧,反正也很简单,iOS封装的太强大了

步骤呢就是这样:

读取二维码需要导入***Foundation框架
#import <***Foundation/***Foundation.h>


1:利用摄像头识别二维码中的内容(模拟器不行)。

2:输入(摄像头)。

3:由会话将摄像头采集到的二维码图像转换成字符串数据。

4:输出(数据)。

5:由预览图层显示扫描场景。

#import "ViewController.h"
#import <***Foundation/***Foundation.h>

@interface ViewController ()<***CaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) ***CaptureSession *session;
@property (nonatomic, strong) ***CaptureVideoPreviewLayer *previewLayer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // 1. 实例化拍摄设备
    ***CaptureDevice *device = [***CaptureDevice defaultDeviceWithMediaType:***MediaTypeVideo];

    // 2. 设置输入设备
    ***CaptureDeviceInput *input = [***CaptureDeviceInput deviceInputWithDevice:device error:nil];

    // 3. 设置元数据输出
    // 3.1 实例化拍摄元数据输出
    ***CaptureMetadataOutput *output = [[***CaptureMetadataOutput alloc] init];
    // 3.3 设置输出数据代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    // 4. 添加拍摄会话
    // 4.1 实例化拍摄会话
    ***CaptureSession *session = [[***CaptureSession alloc] init];
    // 4.2 添加会话输入
    [session addInput:input];
    // 4.3 添加会话输出
    [session addOutput:output];
    // 4.3 设置输出数据类型,需要将元数据输出添加到会话后,才能指定元数据类型,否则会报错
    [output setMetadataObjectTypes:@[***MetadataObjectTypeQRCode]];

    self.session = session;

    // 5. 视频预览图层
    // 5.1 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    ***CaptureVideoPreviewLayer *preview = [***CaptureVideoPreviewLayer layerWithSession:_session];

    preview.videoGravity = ***LayerVideoGravityResizeAspectFill;
    preview.frame = self.view.bounds;
    // 5.2 将图层插入当前视图
    [self.view.layer insertSublayer:preview atIndex:100];

    self.previewLayer = preview;

    // 6. 启动会话
    [_session startRunning];

}

#pragma mark - ***CaptureMetadataOutputObjectsDelegate 代理方法
- (void)captureOutput:(***CaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(***CaptureConnection *)connection
{

    // 会频繁的扫描,调用代理方法
    // 1. 如果扫描完成,停止会话
    [self.session stopRunning];
    // 2. 删除预览图层
    [self.previewLayer removeFromSuperlayer];

    NSLog(@"%@", metadataObjects);
    // 3. 设置界面显示扫描结果

    if (metadataObjects.count > 0) {
        ***MetadataMachineReadableCodeObject *obj = metadataObjects[0];
        // 提示:如果需要对url或者名片等信息进行扫描,可以在此进行扩展!
//        _label.text = obj.stringValue;
        NSLog(@"%@", obj.stringValue);
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: