調(diào)用相機(jī)之前先檢查權(quán)限
如果沒有檢查權(quán)限并作相應(yīng)處理的話厦画,同時(shí)用戶沒有開啟權(quán)限井仰,則用戶使用app調(diào)用攝像頭時(shí)會(huì)發(fā)生崩潰
// 相機(jī)權(quán)限
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusRestricted ||
authStatus == AVAuthorizationStatusDenied) {
// 無權(quán)限进泼,引導(dǎo)用戶開啟權(quán)限
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"未獲得授權(quán)使用攝像頭" message:@"去“設(shè)置>隱私>相機(jī)”開啟一下吧" 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];
}
// 添加預(yù)覽畫面
CALayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
layer.frame = self.view.layer.bounds;
[self.view.layer addSublayer:layer];
[self.captureSession commitConfiguration];
[self.captureSession startRunning];
}