1

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.

Antonio K
  • 144
  • 11

2 Answers2

4

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

DatForis
  • 1,331
  • 12
  • 19
2

For swift 3 :

func askMicroPhonePermission() {
    switch AVAudioSession.sharedInstance().recordPermission() {
    case AVAudioSessionRecordPermission.granted:
        //permissionCheck = true 
    case AVAudioSessionRecordPermission.denied:
       // permissionCheck = false //show alert if required
    case AVAudioSessionRecordPermission.undetermined:
        AVAudioSession.sharedInstance().requestRecordPermission({ (granted) in
            if granted {
                //permissionCheck = true
            } else {
                //permissionCheck = false // show alert if required or completion handler
            }
        })
    default:
        break
    }
}
  • great, all the time I was looking for NSMicrophoneUsageDescription class, thank you :) – Antonio K May 24 '17 at 11:47
  • The requestRecordPermission method is async, and therefore it can not be used to change the value of permissionCheck before the return statement. Instead of a Bool return value you should use a completion handler – DatForis May 24 '17 at 12:31
  • Agreed, We should use completion handler here. –  May 24 '17 at 13:21