从iOS7开始集成了二维码的生成和读取功能,在此前被广泛使用的zbarsdk目前不支持64位处理器
扫描二维码的步骤:
导入AVFoundation框架
-
利用摄像头识别二维码中的内容
- 输入(摄像头)
- 由会话将摄像头采集到的二维码图像转换成字符串数据
- 输出(数据)
- 由预览图层显示扫描场景
代码如下:
//
// ScanQRCodeViewController.m
// 02-扫描二维码
//
// Created by 庞小江 on 2016/11/2.
// Copyright © 2016年 Paul. All rights reserved.
//
#import "ScanQRCodeViewController.h"
#import <AVFoundation/AVFoundation.h>
@interface ScanQRCodeViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, weak) AVCaptureSession *session;
@property (nonatomic, weak) AVCaptureVideoPreviewLayer *layer;
@end
@implementation ScanQRCodeViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self createScanQRCode];
}
- (void)createScanQRCode {
// 1.创建捕捉回话
AVCaptureSession *session = [[AVCaptureSession alloc] init];
self.session = session;
// 2.添加输入设备(数据从摄像头输入)
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
[session addInput:input];
// 3.添加输出数据
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
// 设置代理
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[session addOutput:output];
// 3.1设置输入元数据的类型
[output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
// 4.添加扫描图层
AVCaptureVideoPreviewLayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
layer.frame = self.view.bounds;
[self.view.layer addSublayer:layer];
self.layer = layer;
// 5.开始扫描
[session startRunning];
}
#pragma mark - 实现output的回调方法
// 当扫描到数据时就会执行该方法
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
if (metadataObjects.count > 0) {
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
// 停止扫描
[self.session stopRunning];
// 将预览图层移除
[self.layer removeFromSuperlayer];
} else {
NSLog(@"没有扫描到数据");
}
}