参考demo AppleVideoCapturer
请求录制权限
- Requesting Authorization for Media Capture on iOS
- Requesting Authorization for Media Capture on macOS
-
配置Info.plist
- If your app uses device cameras, include the NSCameraUsageDescription key in your app’s Info.plist file.
- If your app uses device microphones, include the NSMicrophoneUsageDescription key in your app’s Info.plist file.
-
请求/验证权限
switch AVCaptureDevice.authorizationStatus(for: .video) { case .authorized: // The user has previously granted access to the camera. self.setupCaptureSession() case .notDetermined: // The user has not yet been asked for camera access. AVCaptureDevice.requestAccess(for: .video) { granted in if granted { self.setupCaptureSession() } } case .denied: // The user has previously denied access. return case .restricted: // The user can't grant access due to restrictions. return }
注意
+ (void)requestAccessForMediaType:(AVMediaType)mediaType completionHandler:(void (^)(BOOL granted))handler API_AVAILABLE(macos(10.14), ios(7.0));
关于请求授权的api,在macos(10.14)
以后才可以使用。
参考实现 AVCam: Building a Camera App
- 如果还未决定授权状态,将配置session队列挂起,请求授权
- 当获得权限之后,唤醒队列,继续配置session
- 实现的很巧妙
// Communicate with the session and other session objects on this queue.
self.sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
self.setupResult = AVCamSetupResultSuccess;
/*
Check video authorization status. Video access is required and audio
access is optional. If audio access is denied, audio is not recorded
during movie recording.
*/
switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
{
case AVAuthorizationStatusAuthorized:
{
// The user has previously granted access to the camera.
break;
}
case AVAuthorizationStatusNotDetermined:
{
/*
The user has not yet been presented with the option to grant
video access. We suspend the session queue to delay session
setup until the access request has completed.
Note that audio access will be implicitly requested when we
create an AVCaptureDeviceInput for audio during session setup.
*/
dispatch_suspend(self.sessionQueue);
[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
if (!granted) {
self.setupResult = AVCamSetupResultCameraNotAuthorized;
}
dispatch_resume(self.sessionQueue);
}];
break;
}
default:
{
// The user has previously denied access.
self.setupResult = AVCamSetupResultCameraNotAuthorized;
break;
}
}
/*
Setup the capture session.
In general, it is not safe to mutate an AVCaptureSession or any of its
inputs, outputs, or connections from multiple threads at the same time.
Don't perform these tasks on the main queue because
AVCaptureSession.startRunning() is a blocking call, which can
take a long time. We dispatch session setup to the sessionQueue, so
that the main queue isn't blocked, which keeps the UI responsive.
*/
dispatch_async(self.sessionQueue, ^{
[self configureSession];
});