需要导入的库库
开始创建代码
- 全局变量设置
@property (strong,nonatomic)AVCaptureDevice *device;//摄像头
@property (strong,nonatomic)AVCaptureDeviceInput *input;//输入对象
@property (strong,nonatomic)AVCaptureMetadataOutput *output;//输入对象
@property (strong,nonatomic)AVCaptureSession *session;//会话器
@property (strong,nonatomic)AVCaptureVideoPreviewLayer *preview;//layer层承载控件 - 需要遵守的代理
AVCaptureMetadataOutputObjectsDelegate
- 初始化扫描器与开启扫描
// Device
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// Input
_input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
// Output
_output = [[AVCaptureMetadataOutput alloc]init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
// Session
_session = [[AVCaptureSession alloc]init];
[_session setSessionPreset:AVCaptureSessionPresetHigh];
[_session addInput:self.input];
[_session addOutput:self.output];
// 条码类型 AVMetadataObjectTypeQRCode
_output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
// Preview
_preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
_preview.frame =CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64);
[self.view.layer insertSublayer:self.preview atIndex:0];
// 开启扫描
[_session startRunning];
扫描结果的代理方法
#pragma mark AVCaptureMetadataOutputObjectsDelegate - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection { NSString *stringValue; if ([metadataObjects count] >0) { AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0]; stringValue = metadataObject.stringValue; } [_session stopRunning]; }