Type Method

requestAuthorization(_:)

Asks the user to grant your app permission to perform speech recognition.

Declaration

class func requestAuthorization(_ handler: @escaping (SFSpeechRecognizerAuthorizationStatus) -> Void)

Parameters

handler

A block that is called when the authorization request has been approved or denied. The block takes one parameter, status, which contains an authorization status value. The handler does not guarantee a particular execution context.

Discussion

Before you call this method, be sure to add a usage description to your app's Info.plist file that explains why your app wants to perform speech recognition. When the user interacts with an app feature that depends on speech recognition, call this method to present an alert that displays your description and asks for the user's permission, as shown here.

Listing 1

Requesting the user's permission to begin speech recognition

SFSpeechRecognizer.requestAuthorization { authStatus in
            /* The callback may not be called on the main thread. Add an
                operation to the main queue to update the record button's state.
            */
            OperationQueue.main.addOperation {
                switch authStatus {
                    case .authorized:
                        self.recordButton.isEnabled = true
                    case .denied:
                        self.recordButton.isEnabled = false
                        self.recordButton.setTitle("User denied access to speech recognition", for: .disabled)
                    case .restricted:
                        self.recordButton.isEnabled = false
                        self.recordButton.setTitle("Speech recognition restricted on this device", for: .disabled)
                    case .notDetermined:
                        self.recordButton.isEnabled = false
                        self.recordButton.setTitle("Speech recognition not yet authorized", for: .disabled)
                }
            }
        }

The completion handler updates the status based on the user's or device's response to the request. It can work well to dispatch the operation to the main queue if your app updates the user interface according to the authorization status.

See Also

Getting the User's Permission

class func authorizationStatus() -> SFSpeechRecognizerAuthorizationStatus

Returns the status of the authorization request to perform speech recognition.