iOS開發麥克風權限判斷

在iOS開發中,我們經常要使用系統的各種權限!我們需要向系統進行申請,如果不申請會直接造成APP的閃退!
首先我們需要在info.plist文件中,加入以下代碼

<key>NSMicrophoneUsageDescription</key>
<string>請允許使用麥克風進行*****</string>

在進行麥克風使用時候,我們需要對權限進行判斷,我們是否有權限使用麥克風
引入頭文件

#import <AVFoundation/AVFoundation.h>

加入以下權限判斷代碼

  AVAuthorizationStatus microPhoneStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (microPhoneStatus) {
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
        {
            // 被拒絕
            [self goMicroPhoneSet];
        }
            break;
        case AVAuthorizationStatusNotDetermined:
        {
            // 沒彈窗
            [self requestMicroPhoneAuth];
        }
            break;
        case AVAuthorizationStatusAuthorized:
        {
            // 有授權
        }
            break;

        default:
            break;
    }

如果還有進行申請,要進行權限申請

-(void) requestMicroPhoneAuth
{
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {

    }];
}

如果用戶沒有允許,可以進行彈窗提示,進入設置頁面,讓用戶進行選擇

-(void) goMicroPhoneSet
{
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"您還沒有允許麥克風權限" message:@"去設置一下吧" preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];
    UIAlertAction * setAction = [UIAlertAction actionWithTitle:@"去設置" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [UIApplication.sharedApplication openURL:url options:nil completionHandler:^(BOOL success) {

            }];
        });
    }];

    [alert addAction:cancelAction];
    [alert addAction:setAction];

    [self presentViewController:alert animated:YES completion:nil];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。