1 首先使APP获得相机使用权限
在plist文件中用source code的方式打开,添加如下代码:
<key>NSCameraUsageDescription</key>
<string>cameraDesciption</string>
如果没有使应用获取相机使用权限,则使用过程中会崩溃。
2 判断权限
也就是针对是否获得相机使用权限做检验:
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
dispatch_async(dispatch_get_main_queue(), ^{
if (granted) {
//配置扫描view
[self loadScanView];
} else {
NSString *title = @"请在iPhone的”设置-隐私-相机“选项中,允许App访问你的相机";
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
[alertView show];
}
});
}];
3 配置扫描view
- (void)loadScanView {
//1.初始化捕捉设备(AVCaptureDevice),类型为AVMediaTypeVideo
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
//2.用captureDevice创建输入流
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:nil];
//3.创建媒体数据输出流
AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
//4.实例化捕捉会话
_captureSession = [[AVCaptureSession alloc] init];
//4.1.将输入流添加到会话
[_captureSession addInput:input];
//4.2.将媒体输出流添加到会话中
[_captureSession addOutput:output];
//5.设置代理 在主线程里刷新
[output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
//5.2.设置输出媒体数据类型为QRCode
[output setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
//6.实例化预览图层
_videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
//7.设置预览图层填充方式
[_videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
//8.设置图层的frame
[_videoPreviewLayer setFrame:_viewPreview.layer.bounds];
//9.将图层添加到预览view的图层上
[_viewPreview.layer addSublayer:_videoPreviewLayer];
//10.设置扫描范围
output.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.8f, 0.8f);
//10.1.扫描框
_boxView = [[UIView alloc] initWithFrame:CGRectMake(_viewPreview.bounds.size.width * 0.2, _viewPreview.bounds.size.height*0.2, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f, _viewPreview.bounds.size.width - _viewPreview.bounds.size.width * 0.4f)];
_boxView.layer.borderColor = [UIColor redColor].CGColor;
_boxView.layer.borderWidth = 1.0;
[_viewPreview addSubview:_boxView];
_scanLayer = [[CALayer alloc] init];
_scanLayer.frame = CGRectMake(0, 0, _boxView.bounds.size.width, 1);
_scanLayer.backgroundColor = [UIColor blackColor].CGColor;
[_boxView.layer addSublayer:_scanLayer];
[self startRunning];
}
这里我们用到rectOfInterest 这个cgrect跟平时用的不一样,在这里用的是比例来表示,也就是利用这个可以设置扫描的方框的范围
4 开始扫描
#pragma mark 开始
- (void)startRunning {
if (self.captureSession) {
self.isReading = YES;
[self.captureSession startRunning];
_timer=[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(moveUpAndDownLine) userInfo:nil repeats: YES];
}
}
5 扫描线移动
- (void)moveUpAndDownLine {
CGRect frame = self.scanLayer.frame;
if (_boxView.frame.size.height < self.scanLayer.frame.origin.y) {
frame.origin.y = 0;
self.scanLayer.frame = frame;
} else {
frame.origin.y += 5;
[UIView animateWithDuration:0.2 animations:^{
self.scanLayer.frame = frame;
}];
}
}
6 AVCaptureMetadataOutputObjectsDelegate
这个是里面用到的最重要的方法,在这个代理方法里我们可以获得扫描二维码解析出来的数据,然后在里面进行操作
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
//判断是否有数据
if (!_isReading) {
return;
}
if (metadataObjects.count > 0) {
_isReading = NO;
AVMetadataMachineReadableCodeObject *metadataObject = metadataObjects[0];
NSString *result = metadataObject.stringValue;
if (self.resultBlock) {
self.resultBlock(result?:@"");
}
[self.navigationController popViewControllerAnimated:NO];
}
}
7 退出时记得关闭
#pragma mark 结束
- (void)stopRunning {
if ([_timer isValid]) {
[_timer invalidate];
_timer = nil ;
}
[self.captureSession stopRunning];
[_scanLayer removeFromSuperlayer];
[_videoPreviewLayer removeFromSuperlayer];
}