如何在iOS上检测用户授予麦克风权限? [英] How to detect user giving microphone permission on iOS?

查看:1402
本文介绍了如何在iOS上检测用户授予麦克风权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以问题是我需要在用户给出(或拒绝)使用麦克风的权限后调用某个函数。

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

我已经看到了这个:

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

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

然而,这仅用于检测当前状态。

However, this works only to detect current state.

如果当前状态为no且弹出窗口显示且用户给出了权限 - 则不会调用该函数。那是因为在执行此操作的那一刻,权限是否,直到我们下次运行代码时才会调用该函数。

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".

任何人都知道怎么做?

编辑:
忘了提及它必须是iOS 7.0兼容的解决方案。

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

推荐答案

一种方法在iOS 8中引入的 AVAudioSession recordPermission 。这将返回名为 AVAudioSessionRecordPermission 的枚举。您可以使用开关来确定是否已向用户显示权限警报。这样,只有在未向用户显示 requestRecordPermission 时才会调用 requestRecordPermission ,因此权限块可以假定在用户第一次允许或禁止权限后执行它。

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.

一个例子是 -

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;
}

这篇关于如何在iOS上检测用户授予麦克风权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆