简单使用

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <SafariServices/SafariServices.h> // iOS9新增

@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>

/** 输入设备 */
@property (nonatomic, strong) AVCaptureDeviceInput *deviceInput;

/** 输出数据 */
@property (nonatomic, strong) AVCaptureMetadataOutput *metadataOutput;

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

/** 特殊的layer */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;

@end



@implementation ViewController

/**

 * 二维码扫描的实现思路



 1. 创建输入设备 --> 摄像头来收集信息
 2. 创建输出数据 --> 转换为输出数据
 3. 会话类 --> 绑定输入和输出
 4. 创建特殊的Layer --> 用于显示扫描到的数据(不添加layer 可以扫面 但不显示)
 5. 开启会话

 注意: iOS7之前没有二维码扫描功能
 之前使用的第三方框架 ZBar / ZXing
 iOS7系统集成二维码功能 就是集成ZXing到系统之中

 */

- (void)viewDidLoad {
 [super viewDidLoad];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

 // 创建输入设备
 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

 self.deviceInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:nil];

 self.metadataOutput = [[AVCaptureMetadataOutput alloc] init];

 // 会话
 self.session = [[AVCaptureSession alloc] init];

 // 会话绑定输入输出
 if ([self.session canAddInput:self.deviceInput]) {

 [self.session addInput:self.deviceInput];
 }

 if ([self.session canAddOutput:self.metadataOutput]) {

 [self.session addOutput:self.metadataOutput];
 }

 // 设置扫描的数据类型
 [self.metadataOutput setMetadataObjectTypes:@[

 AVMetadataObjectTypeQRCode // 二维码

 ]];



 // 设置代理 监听扫描到的数据
 [self.metadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

 // 特殊的layer
 self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];

 self.previewLayer.frame = self.view.bounds;

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

 // 开启会话
 [self.session startRunning];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate 代理方法
/**
 * 扫描到数据
 */
- (void)captureOutput:(AVCaptureOutput *)captureOutput 
didOutputMetadataObjects:(NSArray *)metadataObjects
       fromConnection:(AVCaptureConnection *)connection {

 // 关闭会话 停止扫描
 [self.session stopRunning];

 // 移除layer
 [self.previewLayer removeFromSuperlayer];

 for (AVMetadataMachineReadableCodeObject *object in metadataObjects) {

    NSLog(@"二维码内容: %@",object.stringValue);

 // 如果发现是网址 就显示网页信息
 if ([object.stringValue hasPrefix:@"http"]) {

 // 创建 SFSafariViewController 对象
 SFSafariViewController *safariVC = [[SFSafariViewController alloc] 
                                     initWithURL:[NSURL URLWithString:object.stringValue]];

 [self presentViewController:safariVC animated:YES completion:nil];
 }

 }

}

results matching ""

    No results matching ""