调用相机之前先检查权限
如果没有检查权限并作相应处理的话,同时用户没有开启权限,则用户使用app调用摄像头时会发生崩溃
// 相机权限
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted ||
authStatus == AVAuthorizationStatusDenied) {
// 无权限,引导用户开启权限
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"未获得授权使用摄像头" message:@"去“设置>隐私>相机”开启一下吧" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[[UIApplication sharedApplication] openURL:url];
}];
[alertController addAction:confirmAction];
[self presentViewController:alertController animated:YES completion:nil];
}
} else {
self.captureSession = [[AVCaptureSession alloc] init];
[self.captureSession beginConfiguration];
AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
// 输入
NSError *error = nil;
AVCaptureDeviceInput *captureInput = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
if (error == nil) {
if ([self.captureSession canAddInput:captureInput]) {
[self.captureSession addInput:captureInput];
} else {
NSLog(@"Input Error %@", error);
}
}
// 输出
AVCaptureMetadataOutput *captureOutput = [[AVCaptureMetadataOutput alloc] init];
[captureOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
if ([self.captureSession canAddOutput:captureOutput]) {
[self.captureSession addOutput:captureOutput];
captureOutput.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code];
}
// 添加预览画面
CALayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
layer.frame = self.view.layer.bounds;
[self.view.layer addSublayer:layer];
[self.captureSession commitConfiguration];
[self.captureSession startRunning];
}