Article

Dispatching Intents to Handler Objects

Provide SiriKit with an object capable of handling a given intent.

Overview

When a user makes a request of your app using Siri or Maps, SiriKit loads your Intents app extension and creates an instance of its INExtension subclass. The job of your extension object is to provide SiriKit with the handler objects that you use to handle specific intents. You provide these objects from the handler(for:) method of your extension object.

The structure of the handler(for:) method is the same for all Intents app extensions, and that method must return a valid new object for all intents that your Intents app extension supports. Listing 1 shows a version of the method that supports intents in the messages and VoIP calling domains. After checking the type of the provided intent object, the method creates and returns an object capable of handling that intent.

Listing 1

Providing handler objects to SiriKit

override func handler(for intent: INIntent) -> Any {
   switch intent {
   case is INSendMessageIntent,
            is INSearchForMessagesIntent,
            is INSetMessageAttributeIntent:
      return MyMessageHandler()
            
   case is INStartAudioCallIntent:
      return MyAudioCallHandler()
            
   case is INStartVideoCallIntent:
      return MyVideoCallHandler()
            
   default:
      // The app extension should only be called for intents it knows about.
      fatalError()
   }
}

The object you return from the handler(for:) method must implement the specific protocol needed to handle the corresponding intent. Each intent object has an associated protocol whose name is based on the name of the intent. For example, when handling an INStartAudioCallIntent object, you provide an object that adopts the INStartAudioCallIntentHandling protocol. The protocol defines the methods that your object must implement to resolve any intent parameters and to let SiriKit know how you handled the intent.

SiriKit typically creates multiple copies of your handler object when processing a single intent object and calls only one method on each object. Do not store cached state information in a handler object because that information will not be present during subsequent method calls. Instead, always make fresh requests for any needed data from each of your methods.

See Also

Siri Intents

Creating an Intents App Extension

Add and configure an Intents app extension in your Xcode project.

Structuring Your Code to Support App Extensions

Move your back-end services to a private framework so your app and app extensions can use them.

Resolving and Handling Intents

Resolve, confirm, and handle user requests for your app’s services.

protocol INIntentHandlerProviding

The interface for dispatching intents to the custom objects that handle those intents.

Extension-Related Classes

Learn about the classes you use to build your Intents extension.