一.需要包含头文件
#import <AVFoundation/AVFoundation.h>
二.通过设置<AVCaptureMetadataOutputObjectsDelegate>代理可以监听扫描到的二维码中的信息
三.具体代码
1 #import "ViewController.h" 2 #import3 4 @interface ViewController () 5 6 @end 7 8 @implementation ViewController 9 10 - (void)viewDidLoad {11 [super viewDidLoad];12 }13 14 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event15 {16 // 1.创建捕捉会话17 AVCaptureSession *session = [[AVCaptureSession alloc] init];18 19 // 2.设置输入设备20 AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];21 AVCaptureDeviceInput *inputDevice = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];22 [session addInput:inputDevice];23 24 // 3.设置输入方式25 AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];26 [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];27 [session addOutput:output];28 [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];29 30 // 4.添加一个显示的layer31 AVCaptureVideoPreviewLayer *layer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];32 layer.frame = self.view.bounds;33 [self.view.layer addSublayer:layer];34 35 // 5.开始扫描36 [session startRunning];37 }38 39 #pragma mark - 获取扫描结果40 - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection41 {42 if (metadataObjects.count > 0) {43 AVMetadataMachineReadableCodeObject *object = [metadataObjects lastObject];44 NSLog(@"%@", object.stringValue);45 }46 }47 48 @end