Search code examples
iosswift3microphoneprivacy-policy

how to check NSMicrophoneUsageDescription programmatically


I want that the user use the microphone in the app, and add the appropriate key to the info.plist "Privacy-MicrophoneUsageDescription", If user tap the microphone button, window with a question for usage permission appears. If the user taps on "Allow", the app works fine without some issues. But if not, and press the microphone button again, the app crashes.

What I want is, to check for the NSMicrophoneUsageDescription status, every time the button is pressed. If denied, ask the user for the permission again.


Solution

  • The selected answer won't work the requestRecordPermission method is async and it won't change the value of permissionCheck before the value is returned in the return statement the correct way to go about it is using a completion handler

    func askMicroPhonePermission(completion: @escaping (_ success: Bool)-> Void) {
        switch AVAudioSession.sharedInstance().recordPermission() {
        case AVAudioSessionRecordPermission.granted:
            completion(true)
        case AVAudioSessionRecordPermission.denied:
            completion(false) //show alert if required
        case AVAudioSessionRecordPermission.undetermined:
            AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
                if granted {
                    completion(true)
                } else {
                    completion(false) // show alert if required
                }
            })
        default:
            completion(false)
        }
    }
    

    I modified the selected answer to include a completion handler instead of it having a return statement