Search code examples
swiftmacoscameraprivacymacos-mojave

Request camera permissions in macOS Mojave


Initializing an AVCaptureDeviceInput for a camera fails in macOS Mojave if the user has not granted permissions. When trying to initialize, the system automatically presents the permission request dialog. There seems to be no way though to get notified of the user response.

I'm looking for an analog way to get notified as with requesting audio permissions in:

The Protecting the User's Privacy guide does not outline any other methods for camera access.


Solution

  • Found that the solution is actually analog to iOS by checking authorizationStatus(for:) on AVCaptureDevice before initializing an AVCaptureDeviceInput from it.

    And using requestAccess(for:completionHandler:) to request the permission if needed.

    An example for getting camera access:

    let status = AVCaptureDevice.authorizationStatus(for: .video)
    
    if status == .authorized {
      // connect to video device
      let devices = AVCaptureDevice.devices(for: .video)
      ...
      return
    }
    
    if status == .denied {
      // show error
      return
    }
    
    AVCaptureDevice.requestAccess(for: .video) { (accessGranted) in
      // handle result
    }