How to open app when indexed entity is tapped in Spotlight?

Asked on 08/07/2024

1 search

To open an app when an indexed entity is tapped in Spotlight, you need to follow these steps:

  1. Conform to the IndexedEntity Protocol: First, ensure that your entity conforms to the new IndexedEntity protocol. This allows your app's entities to be indexed by Spotlight.

  2. Index Your Entities: In your app's initialization method, index all the entities using CSSearchableIndex. This can be done by calling indexAppEntities on CSSearchableIndex.

  3. Implement an Intent: Create an intent that can handle the entity. For example, if you have a trail entity, you might have an OpenTrailIntent that accepts a trail entity as a parameter.

  4. Search and Tap: When a user searches for the entity in Spotlight and taps on the result, the intent will be triggered, and the app will open to the relevant content.

Here is a more detailed breakdown from the session "What’s new in App Intents":

  • Indexing the Entity:

    // Add conformance to IndexedEntity protocol
    struct Trail: IndexedEntity {
        // Implementation details
    }
    
    // Indexing entities in the app's init method
    let trails = dataManager.getAllTrails()
    CSSearchableIndex.default().indexAppEntities(trails)
    
  • Handling the Tap:

    • Ensure you have an intent that can handle the entity. For example, OpenTrailIntent:
    struct OpenTrailIntent: AppIntent {
        @Parameter(title: "Trail") var trail: Trail
    
        func perform() async throws -> some IntentResult {
            // Open the app to the specific trail
        }
    }
    

When the user taps on the search result in Spotlight, the OpenTrailIntent will be triggered, and the app will navigate to the specific trail.

For more details, you can refer to the session "What’s new in App Intents".