在请求使用iPhone 11的iPhone麦克风时,应用程序崩溃

时间:2017-10-14 02:24:29

标签: swift ios11 avaudiosession avaudiorecorder

当我尝试使用以下代码请求使用iPhone麦克风的权限时,我的应用程序崩溃了:

var permissionGranted = false
switch AVAudioSession.sharedInstance().recordPermission() {
case AVAudioSessionRecordPermission.granted:
    setupRecorder()
    permissionGranted = true
case AVAudioSessionRecordPermission.denied:
    permissionGranted = false
case AVAudioSessionRecordPermission.undetermined:
    AVAudioSession.sharedInstance().requestRecordPermission {
        [weak self] granted in
        if granted {
            self?.setupRecorder()
        }
    }
default:
    permissionGranted = false
    break
}

我还在应用程序的Info.plist中添加了NSMicrophoneUsageDescription字符串。当我运行应用程序时,它会崩溃并且Xcode会打印一条错误消息,说我需要将NSMicrophoneUsageDescription添加到plist。

1 个答案:

答案 0 :(得分:0)

尝试使用以下功能

 struct Manager {
    static var recordingSession: AVAudioSession!
    static var micAuthorised = Bool()        
}

func CheckForPermission()
    {
        Manager.recordingSession = AVAudioSession.sharedInstance()
        do
        {
            try Manager.recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
//            try Manager.recordingSession.setPreferredSampleRate(16000)
//            try Manager.recordingSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
//            try Manager.recordingSession.setActive(true)
            Manager.recordingSession.requestRecordPermission({ (allowed) in
                if allowed
                {
                    Manager.micAuthorised = true
                    print("Mic Authorised")
                }
                else
                {
                    Manager.micAuthorised = false
                    print("Mic not Authorised")
                }
            })
        }
        catch
        {
            print("Failed to set Category", error.localizedDescription)
        }
    }