Skip to main content

Working with App Intents Framework

1. Defining App Intents

Property Description Example
intent The intent type that defines the user's goal Intent
parameters Input values required to fulfill the intent String
responses Output values or actions to perform String

Example: Defining a Simple Intent

import AppIntents

struct GreetingIntent: AppIntent {
    static var title: LocalizedStringResource = "Greet User"
    
    @Parameter(title: "Name")
    var name: String
    
    func run() async throws -> some AppIntentResult {
        return .result(value: "Hello, \(name)!")
    }
}
Note: App Intents must be declared in the app's Info.plist and registered with the system to be available for Siri Shortcuts.

2. Creating Intent Parameters

Parameter Type Description Notes
intentParameter IntentParameter<String> Defines a parameter for an intent Used to specify input values for an intent
intentParameter IntentParameter<Int> Defines a parameter for an intent Used to specify integer input values for an intent
intentParameter IntentParameter<Bool> Defines a parameter for an intent Used to specify boolean input values for an intent

Example: Defining Intent Parameters

import AppIntents

struct MyIntent: Intent {
    @Parameter(title: "Name") var name: String
    @Parameter(title: "Age") var age: Int
    @Parameter(title: "Is Active") var isActive: Bool
}

3. Implementing perform() Method

Method Description Return Type Notes
func perform() Executes the intent action Result<Void, Error> Required for all custom intents

Example: Implementing perform() in a Custom Intent

import AppIntents

struct MyIntent: AppIntent {
    static var title: LocalizedStringResource = "My Custom Intent"
    
    func perform() async throws {
        // Perform the action here
        print("Executing MyIntent")
    }
}
Note: The perform() method is called when the user triggers the intent.

4. Using Intent Shortcuts

Property Description Example
intent The intent to be triggered by the shortcut IntentType.openApp
title Display name for the shortcut in Settings "Open My App"
subtitle Subtitle shown in Settings for the shortcut "Launch app quickly"
icon Icon to represent the shortcut (must be a valid SF Symbol name) "app.badge"

Example: Define an Intent Shortcut

import AppIntents

struct OpenAppIntent: Intent {
    static var title: LocalizedStringResource = "Open My App"
    static var description: LocalizedStringResource = "Launch app quickly"

    init() {}

    func run() async throws {
        // Launch the app or perform an action
    }
}

struct OpenAppShortcut: AppIntentShortcut {
    static var intent = OpenAppIntent()
    static var title = "Open My App"
    static var subtitle = "Launch app quickly"
    static var icon = "app.badge"
}
Note: Intent shortcuts must be registered in your app's Info.plist under the NSUserActivityTypes key to be recognized by Siri and the Shortcuts app.

5. Integrating with Siri

App Intents allows you to integrate your app's functionality with Siri, enabling users to interact with your app through voice commands.

Feature Description Notes
Siri Intent Defines the intent that Siri can trigger. Must be declared in Info.plist
Intent Handler Class that handles the intent when triggered by Siri. Conforms to INExtension
Intent Definition Defines the structure and parameters of the intent. Created using Xcode's Intent Definition file

Example: Defining an Intent

import Intents

struct MyIntent: INIntent {
    let name = "MyIntent"
    let description = "Performs a custom action"
}

Example: Handling the Intent

import Intents

class IntentHandler: INExtension {
    override func handler(for intent: INIntent) -> Any {
        return self
    }
}
Note: Ensure that your app's Info.plist includes the necessary permissions and configurations for Siri integration.
Warning: App Intents requires the app to be built with iOS 15 or later.

6. Providing Intent Suggestions

Property Description Values
intent The intent to provide suggestions for Intent
suggestions List of suggested values for the intent [IntentSuggestion]

Example: Defining Intent Suggestions

import AppIntents

struct MyIntent: AppIntent {
    static var title: LocalizedString = "My Intent"
    
    @Parameter(title: "Name")
    var name: String
    
    static func suggestions(for parameter: Name) -> [IntentSuggestion] {
        [
            IntentSuggestion("John"),
            IntentSuggestion("Jane")
        ]
    }
}
Note: Intent suggestions are used to provide context-aware completions in Siri and Shortcuts.

7. Using App Shortcuts

App Shortcuts allow users to quickly launch specific actions within your app using Siri or the Home Screen.

Property Description Example
intent The intent that defines the action to be performed. Intent
title The title displayed in the Siri Shortcuts UI. "Open Recent Notes"
subtitle Optional subtitle for additional context. "View your last 5 notes"
icon Icon to represent the shortcut in the UI. AppIntentImage(systemName: "doc.text")

Example: Defining an App Shortcut

import AppIntents

struct OpenRecentNotesIntent: AppIntent {
    static var title: LocalizedStringResource = "Open Recent Notes"
    
    static var description: IntentDescription = "Opens the most recently created notes."
    
    @Parameter(title: "Notes Count", default: 5)
    var count: Int
    
    func perform() async throws -> some IntentResult {
        return .result(value: "Opened \(count) recent notes")
    }
}

struct OpenRecentNotesShortcut: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        AppShortcut(
            intent: OpenRecentNotesIntent(),
            title: "Open Recent Notes",
            subtitle: "View your last 5 notes",
            icon: AppIntentImage(systemName: "doc.text")
        )
    }
}
Note: App Shortcuts must be declared in the AppShortcutsProvider struct and registered in your app's Info.plist.
Warning: Ensure that the intent's perform method handles errors gracefully to prevent crashes when Siri executes the shortcut.

8. Creating Focus Filters

Property Description Values
FocusFilter Defines a filter to apply to focus mode FocusFilter
focusFilter Instance of FocusFilter FocusFilter()

Example: Creating a Focus Filter

import AppIntents

struct MyFocusFilter: FocusFilter {
    static let title = "My Focus Filter"
    static let description = "A custom focus filter for specific apps"
    
    func evaluate() async throws -> FocusFilterResult {
        return .include
    }
}
Note: Focus filters are used to define conditions under which a focus mode applies.
Warning: Focus filters must be registered in your app's Info.plist to be active.

9. Implementing Entity Queries

Entity queries in the App Intents framework allow you to define and handle specific data entities that your app can work with. These queries are used to fetch or update information related to these entities.

Property Type Description
intent Intent The intent associated with the entity query.
entities [Entity] An array of entities to query.
query String The query string used to filter or search for entities.

Example: Fetching Entities

import AppIntents

struct MyEntityQuery: EntityQuery {
    func entities(for search: String) async throws -> [MyEntity] {
        // Fetch entities based on search query
        return []
    }
    
    func entity(for identifier: String) async throws -> MyEntity? {
        // Fetch a specific entity by identifier
        return nil
    }
}

Example: Defining an Entity

import AppIntents

struct MyEntity: AppEntity {
    let name: String
    let identifier: String
    
    static var typeDisplayRepresentation: TypeDisplayRepresentation {
        "My Entity"
    }
    
    static var defaultQuery: MyEntityQuery {
        MyEntityQuery()
    }
}

10. Combining Intents with Widgets

App Intents can be combined with widgets to provide rich, interactive experiences on the Home Screen. This integration allows users to trigger actions or view dynamic content directly from their widgets.

Feature Description Usage
Intent An intent represents a user action that can be performed in your app. Define an intent using Intent class and implement the IntentHandler.
Widget A widget displays information or allows interaction with your app on the Home Screen. Use AppIntent to define actions that can be triggered from widgets.

Example: Creating a Widget with App Intent

import WidgetKit
import SwiftUI

struct MyWidgetEntryView : View {
    var entry: Provider.Entry

    var body: some View {
        VStack {
            Text("Hello, World!")
                .onTapGesture {
                    // Trigger an App Intent here
                }
        }
    }
}

struct MyWidget: Widget {
    let kind: String = "MyWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            MyWidgetEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

struct Provider: IntentTimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), configuration: ConfigurationIntent())
    }

    func timeline(for configuration: ConfigurationIntent, in context: Context) -> Timeline<SimpleEntry> {
        let entries: [SimpleEntry] = [
            SimpleEntry(date: Date(), configuration: configuration)
        ]
        return Timeline(entries: entries, policy: .after(Date().addingTimeInterval(60 * 60)))
    }
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let configuration: ConfigurationIntent
}
Note: Widgets must be configured to support App Intents through the Intent class and appropriate handler methods.
Warning: Ensure that the widget's configuration aligns with the intent's capabilities to avoid runtime errors.

Was this article helpful?