How to detect user giving microphone permission on iOS?

╄→гoц情女王★ 提交于 2019-12-19 06:50:08

问题


So the thing is that I need to call some function after user gives (or declines) a permission to use the microphone.

I already saw this:

[[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            // Microphone enabled code
            [self someFunction];

        }
        else {
            // Microphone disabled code
        }
 }];

However, this works only to detect current state.

If the current state is "no" and popup shows and user gives the permission - the function will not be called. That's because in the moment of executing this the permission was "no" and until we run the code next time the function will not be called.

What I want to do is to call a function after the user pressed either "allow" or "decline".

Anyone knows how to do this?

EDIT: Forgot to mention it has to be iOS 7.0 up compatible solution.


回答1:


A method of AVAudioSession introduced in iOS 8 is recordPermission. This returns an enum named AVAudioSessionRecordPermission. You could use a switch to determine whether the permission alert has been presented to the user or not. This way you only call requestRecordPermission when it has not been presented to the user, so the permission block can assume it is being executed after the user allows or disallows permission for the first time.

An example would be something like -

AVAudioSessionRecordPermission permissionStatus = [[AVAudioSession sharedInstance] recordPermission];

switch (permissionStatus) {
     case AVAudioSessionRecordPermissionUndetermined:{
          [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
          // CALL YOUR METHOD HERE - as this assumes being called only once from user interacting with permission alert!
              if (granted) {
                  // Microphone enabled code
              }
              else {
                  // Microphone disabled code
              }
           }];
          break;
          }
     case AVAudioSessionRecordPermissionDenied:
          // direct to settings...
          break;
     case AVAudioSessionRecordPermissionGranted:
          // mic access ok...
          break;
     default:
          // this should not happen.. maybe throw an exception.
          break;
}



回答2:


If use has not yet given your permission, do the following:

  1. First, show the popup dialogue
  2. Run your code in OP

-

if([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission)]) {
    [[AVAudioSession sharedInstance] requestRecordPermission];
    // Now run your function
}


来源:https://stackoverflow.com/questions/33065150/how-to-detect-user-giving-microphone-permission-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!