KVO observe AVAudioSession's recordPermission doesn't work

129 Views Asked by At

My application uses the microphone's permission, which is requested in another framework, and in the main application, I wasn't able to observe when microphone permission changed. I tried using KVO's observer but the application doesn't receive any events when the microphone permission is changed.

private var permissionStatusObserver: NSKeyValueObservation?

private func observeRecordPermissionChange() {
    do {
      try audioSession.setActive(true)
      permissionStatusObserver = audioSession.observe(\.recordPermission) { [weak self] _, recordPermissions in
        print("recordPermission changed")
      }
    } catch {
      print("active audio failed \(error.localizedDescription)")
    }
  }
1

There are 1 best solutions below

2
timbre timbre On

Not going to work.

There are 3 possibilities:

  • App never asked user for permissions yet. In this case you should present permissions to the user and wait for their response. In this case you need to define requestRecordPermission callback instead of listening to KVO.

  • App previously asked user for permissions, and user granted them. In this case you can proceed working with microphone.

  • App previously asked user for permissions, and user denied. Typically in this case apps show the message telling user to go to settings. And user needs to go to Settings -> Privacy -> Microphone and reenable the permissions, at which point the app will be restarted. So nothing to listen to as @cora mentioned.

Something like this:

switch AVAudioSession.sharedInstance().recordPermission {
    case .granted:
       // start recording
    case .denied:
       // Present message to user indicating that recording
       // can't be performed until they change their preference
       // under Settings -> Privacy -> Microphone 
    case . undetermined:
       // Ask for permissions as explained below.
}

Or you can always ask for permissions like Apple tells us to:

// Request permission to record.
AVAudioSession.sharedInstance().requestRecordPermission { granted in
    if granted {
        // The user granted access. Present recording interface.
    } else {
        // Present message to user indicating that recording
        // can't be performed until they change their preference
        // under Settings -> Privacy -> Microphone
    }
}

This is safe to do even if the permission is already granted (the callback will be back very quickly).