iOS监听系统相机、麦克风是否打开

在开发过程中有时候需要自己判断系统相机和麦克风权限来自定义UI界面。可以使用下面的方法来进行判断:

// 监听后面的摄像头是否可用
- (BOOL) isRearCameraAvailable{
    
    __block BOOL bCanRecord = NO;
    
    NSString *mediaType = AVMediaTypeVideo;//读取媒体类型
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];//读取设备授权状态
    if(authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
        bCanRecord = NO;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[[UIAlertView alloc] initWithTitle:@"无法拍摄"
                                        message:@"XXXX需要访问您的相机。\n请启用相机-设置/隐私/相机"
                                       delegate:self
                              cancelButtonTitle:@"关闭"
                              otherButtonTitles:nil] show];
            
        });
        
    }else{
        bCanRecord = YES;
        
    }
    
    return bCanRecord;
}
//监听是否可以录音
-(BOOL)canRecord
{
    __block BOOL bCanRecord = NO;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                bCanRecord = YES;
            }
            else {
                bCanRecord = NO;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [[[UIAlertView alloc] initWithTitle:@"无法录音"
                                                message:@"XXXX需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                               delegate:self
                                      cancelButtonTitle:@"关闭"
                                      otherButtonTitles:nil] show];
                });
            }
        }];
    }
    return bCanRecord;
}

另外,重申一点,网上有些方法在判断权限的时候去加了系统的判断导致无法正确监听。

你可能感兴趣的:(iOS监听系统相机、麦克风是否打开)