1,导入框架,AVFoundation.framework
2,导入头文件并添加属性:
#import "ViewController.h"
#import "AVFoundation/AVFoundation.h"
@interface ViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic,strong) AVCaptureVideoPreviewLayer *layer;
@property (nonatomic,strong) AVCaptureSession *session;
@end
3,设置硬件设备调用方法
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self setScanView];
}
- (void)setScanView{
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];
}
4,添加代理方法,读取扫描数据:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
if (metadataObjects.count > 0) {
//获得扫描数据,最后一个时最新扫描的数据
AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];
NSLog(@"%@", object.stringValue);
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:object.stringValue]];
// 停止扫描
// [self.session stopRunning];
// 将预览图层移除
// [self.layer removeFromSuperlayer];
} else {
NSLog(@"没有扫描到数据");
}
}