onmyway133 / blog

🍁 What you don't know is what you haven't learned
https://onmyway133.com/
MIT License
669 stars 33 forks source link

How to use AppIntents in iOS 16 #930

Open onmyway133 opened 11 months ago

onmyway133 commented 11 months ago

AppIntents

Declare AppShortcutsProvider, note that appShortcuts uses @AppShortcutsBuilder syntax

import AppIntents

struct OurShortcutsProvider: AppShortcutsProvider {
    static var shortcutTileColor: ShortcutTileColor = .lightBlue

    @AppShortcutsBuilder
    static var appShortcuts: [AppShortcut] {
        AppShortcut(intent: AskIntent(), phrases: [
            "Hey Joy",
            "Ask \(.applicationName)"
        ])
    }
}

We can create an app intent in code

import AppIntents
import OpenAI

struct AskIntent: AppIntent {
    static var title: LocalizedStringResource = "Hey Joy"
    static var description: IntentDescription = "Ask me anything"

    @Parameter(title: "Prompt")
    var prompt: String?

    static var parameterSummary: some ParameterSummary {
        Summary("Ask question \(\.$prompt)")
    }

    func perform() async throws -> some ProvidesDialog {
        guard let prompt else {
            throw $prompt.needsValueError("Please provide a question")
        }

        let client = ChatService()
        let content = try await client.ask(prompt: prompt)

        if let content {
            return .result(dialog: IntentDialog(stringLiteral: content))
        } else {
            return .result(dialog: "No valid answer")
        }
    }
}

Update parameters

If the intents have dynamic parameters, we can tell AppIntents to refresh its parameters list, using [updateAppShortcutParameters](https://developer.apple.com/documentation/appintents/appshortcutsprovider/updateappshortcutparameters())

OurShortcutsProvider.updateAppShortcutParameters()

Show tip view

Use SiriTipView

SiriTipView(intent: ReorderIntent(), isVisible: $isVisible)
    .siriTipViewStyle(.black)

Show link to open Shortcuts app

Use ShortcutsLink

ShortcutsLink()
     .shortcutsLinkStyle(.whiteOutline)

Troubleshoot

Look for appintentsmetadataprocessor in build log for potential errors

Some possible warnings

Metadata extraction skipped. No AppIntents.framework dependency found.