Search code examples
iosswiftspeech-to-textapple-speech

SFSpeechRecognizer not authorized cases never entered


I am following a simple tutorial here to get iOS speech recognition working.

Even when a user denies microphone access, when I run it in simulator, it always goes in the authorized case and prints out authorized, even before the user selects Allow in the prompt. MyaskSpeechPermission is never called. How do I fix this?

let audioEngine = AVAudioEngine()
let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))
let request = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask: SFSpeechRecognitionTask?

override func viewDidLoad() {        
    super.viewDidLoad()

    switch SFSpeechRecognizer.authorizationStatus() {
        case .notDetermined:
            askSpeechPermission()
            print("not determined")
        case .authorized:
            self.status = .ready
            print("authorized")
        case .denied, .restricted:
            self.status = .unavailable
            print("denied or restricted")
    }

}

func askSpeechPermission() {
    SFSpeechRecognizer.requestAuthorization { status in
        OperationQueue.main.addOperation {
            switch status {
                case .authorized:
                    self.status = .ready
                default:
                    self.status = .unavailable
            }
        }
    }
}

Solution

  • Welcome to Stack Overflow!

    Once the user authorizes or denies the request, it won't be shown again even if requestAuthorization is called again. If you delete the app from the simulator, then re-run in Xcode, it will clear the prior selection and allow the dialog to appear again.

    I ran the code you posted and appears to work as expected.