This documentation is available as Markdown for AI agents and LLMs. See the full Markdown index or append .md to any documentation URL.

Expo AppIntents

一个用于从 Expo 应用公开 Apple App Intents、Siri、快捷指令、Spotlight 和 Apple 智能入口点的库。

iOS
macOS
tvOS
Recommended version:
~0.5.4

expo-app-intents 可以让你的应用暴露 Apple App Intents。它会把意图声明保存在 Swift 内联模块 中,这样 Apple 的构建时元数据提取就能找到它们。这个包提供了 JavaScript API、本地调用队列、实体存储、配置插件,以及一个用于本地内联模块代码的入门 app-intents 目录。

你不能在运行时通过 JavaScript 动态创建 App Intent 类型。你需要在 Swift 中声明所需的 AppIntent 类型。带参数的意图还需要 AppEntity 和 EntityQuery 类型。如果你的应用支持快捷短语,通常会声明一个 AppShortcutsProvider。当你的应用不使用快捷短语时,比如只暴露 schema 意图,可以省略。使用这个包可以把调用传递给 JavaScript,并保持动态实体值同步。

🌐 You cannot create App Intent types dynamically from JavaScript at runtime. Declare the AppIntent types you need in Swift. Parameterized intents also require AppEntity and EntityQuery types. If your app exposes shortcut phrases, you usually declare an AppShortcutsProvider. You can leave it out when your app does not use shortcut phrases, such as when it exposes only schema intents. Use this package to deliver invocations to JavaScript and keep dynamic entity values in sync.

苹果智能支持

🌐 Apple Intelligence support

使用 expo-app-intents,你可以实现 Apple 智能功能,包括 屏幕上的智能。在 iOS 18.4 及更高版本中,你可以标记视图所表示的实体,这样 Siri 就可以对可见内容进行操作。将 appEntityIdentifier() 修饰符应用到 @expo/ui 视图,或者将 React Native 视图封装在 AppEntityView 中。两者都需要使用 Xcode 27 或更高版本编译项目。在使用较早 Xcode 构建的项目中,视图仍然可以正常渲染,但系统无法将它们与实体关联。

🌐 With expo-app-intents, you can implement Apple Intelligence features, including on-screen intelligence. On iOS 18.4 and later, you can mark the entity represented by a view so Siri can act on the visible content. Apply the appEntityIdentifier() modifier to @expo/ui views, or wrap React Native views in AppEntityView. Both require the project to be compiled with Xcode 27 or later. In a project built with an earlier Xcode, the views still render normally, but the system cannot associate them with the entity.

安装

🌐 Installation

Terminal
- npx expo install expo-app-intents
- yarn expo install expo-app-intents
- pnpm expo install expo-app-intents
- bun expo install expo-app-intents

If you are installing this in an existing React Native app, make sure to install expo in your project.

应用配置中的配置

🌐 Configuration in app config

初始化程序会为你写好所需的配置:

🌐 The initializer writes the required configuration for you:

Example app.json with config plugin

app.json
{ "expo": { "plugins": ["expo-app-intents"], "experiments": { "inlineModules": { "watchedDirectories": ["app-intents"] } } } }

如果你使用的是 app-intents 以外的目录,请在配置插件中传入相同的目录名:

🌐 If you use a directory other than app-intents, pass the same directory name to the config plugin:

Example app.json with config plugin

app.json
{ "expo": { "plugins": [["expo-app-intents", { "directory": "siri" }]], "experiments": { "inlineModules": { "watchedDirectories": ["siri"] } } } }

工作原理

🌐 How it works

App Intents 和大多数 Expo API 不同,因为 Apple 会在构建时发现它们。把描述你的 intents、实体、查询和快捷短语的 Swift 类型编译到应用目标中。Xcode 的 App Intents 元数据处理器就能提取它们。expo-app-intents 为这个应用目标的 Swift 使用了 Expo 内联模块,并提供了一个用于 JavaScript API、本地存储和事件传递的 Expo 包。

🌐 App Intents differ from most Expo APIs because Apple discovers them at build time. Compile the Swift types that describe your intents, entities, queries, and shortcut phrases into the app target. Xcode's App Intents metadata processor can then extract them. expo-app-intents uses Expo inline modules for this app-target Swift and provides an Expo package for the JavaScript API, native storage, and event delivery.

Expo 内联模块会监视生成的 app-intents 目录,其中包含你的应用自有的 Swift 代码:

🌐 Expo inline modules watch the generated app-intents directory, which contains your app-owned Swift code:

  • AppShortcuts.swift 定义了当所选示例使用快捷短语时你的具体 AppShortcutsProvider。快捷短语是静态元数据。构建过程会将它们编译到应用中,JavaScript 无法动态添加它们。
  • AppIntentsSetup.swift 包含所选功能所需的应用目标设置。当应用有一个 AppShortcutsProvider 时,此文件会将 AppShortcuts.updateAppShortcutParameters() 连接到 expo-app-intents 运行时。
  • 剩下的 Swift 文件定义了具体的 AppIntent、AppEntity 和 EntityQuery 类型。它们会被编译进应用目标中。只有当一个文件包含 Expo 模块定义时,Expo 才会把它注册为模块。

当意图运行时,完成 Siri 或快捷指令在其 perform() 方法中所期望的本地工作。然后将意图分发到 JavaScript:

🌐 When an intent runs, complete the native work that Siri or Shortcuts expects in its perform() method. Then dispatch the intent to JavaScript:

await AppIntentDispatcher.shared.dispatch( name: "orderFood", params: ["dishId": .string(dish.id), "dishName": .string(dish.name)] )

AppIntentDispatcher 是一个 Swift actor。它会先在本地存储中记录调用。如果 JavaScript 运行时已经在监听,那么它会发出一个 onIntent 事件。这个过程保证至少一次投递。每次调用都通过 id 来处理,并在应用动作后调用 removePendingInvocationAsync(id)。

如果 Siri 或快捷指令在 JavaScript 未运行时被触发,该调用会保留在待处理队列中。当你的应用启动时,useAppIntents() 会用当前的待处理调用来调用你的处理器,并将 newIntent 设置为 null。每个正在进行的调用会再次用新的调用调用处理器。你也可以用 getPendingInvocationsAsync() 来读取队列。

🌐 If Siri or Shortcuts runs while JavaScript is not running, the invocation stays in the pending queue. When your app starts, useAppIntents() calls your handler with the current pending invocations and sets newIntent to null. Each live invocation calls the handler again with the new invocation. You can also read the queue with getPendingInvocationsAsync().

参数化意图使用本地实体。例如,餐厅模板在 Swift 中定义了 DishEntity 和 DishQuery。JavaScript 使用 setEntityCatalogAsync('dish', dishes) 提供当前的菜品列表。本地查询通过 AppIntentEntityStore.shared 读取该目录,因此 Siri 和快捷指令可以通过标识符、标题或同义词解析语音值。调用 setEntityCatalogAsync() 会替换目录并请求快捷指令参数刷新。每当这些值发生变化时,再次调用即可。

🌐 Parameterized intents use native entities. For example, the restaurant template defines DishEntity and DishQuery in Swift. JavaScript supplies the current dish list with setEntityCatalogAsync('dish', dishes). The native query reads that catalog through AppIntentEntityStore.shared, so Siri and Shortcuts can resolve spoken values by identifier, title, or synonym. Calling setEntityCatalogAsync() replaces the catalog and requests a shortcut parameter refresh. Call it again whenever those values change.

像邮件例子这样的模式意图,也是在 app-target 的 Swift 中定义的。苹果把应用模式域分成两组。Apple Intelligence 和 Siri 可以发现符合 主 域的类型,比如 mail、photos 或 files。而 Shortcuts 专用 的域,比如 journal、books 或 reader,则只出现在 Shortcuts 应用里。

🌐 Schema intents, such as the mail example, are also defined in app-target Swift. Apple divides app schema domains into two groups. Apple Intelligence and Siri can discover types that conform to a primary domain, such as mail, photos, or files. Shortcuts-specific domains, such as journal, books, or reader, appear only in the Shortcuts app.

一个 schema 意图不需要快捷短语。它的 schema 一致性使它可以被发现。Xcode 会在构建时提取 App Intents 元数据,所以 Siri 和快捷指令应用可以在不需要在你的 AppShortcutsProvider 中输入的情况下使用该动作。因此,邮件示例不会贡献任何 AppShortcut。如果你选择的示例都没有贡献,初始化器就不会生成 AppShortcuts.swift。

🌐 A schema intent does not need a shortcut phrase. Its schema conformance makes it discoverable. Xcode extracts the App Intents metadata at build time, so Siri and the Shortcuts app can use the action without an entry in your AppShortcutsProvider. The mail example therefore contributes no AppShortcut. If none of the examples you select contributes one, the initializer does not write AppShortcuts.swift.

当 appShortcuts 的主体不包含任何 AppShortcut 时,Xcode 会拒绝 AppShortcutsProvider 并报错 'AppShortcutsProvider' property 'appShortcuts' requires builder syntax。当你有要声明的短语时,记得添加 AppShortcuts.swift。

🌐 Xcode rejects an AppShortcutsProvider whose appShortcuts body contains no AppShortcut with the error 'AppShortcutsProvider' property 'appShortcuts' requires builder syntax. Add AppShortcuts.swift when you have a phrase to declare.

只有在你想要像“在 MyApp 里点餐”这样的编译启动短语时才添加 AppShortcut。你不能有条件地添加短语,所以引用可用性受限意图的提供者必须使用相同的可用性。在这种情况下,可以考虑写一个普通的封装意图。

🌐 Add an AppShortcut only when you want a compiled launch phrase such as "Order food in MyApp". You cannot add phrases conditionally, so a provider that references an availability-gated intent must use the same availability. In this case, consider writing a plain wrapper intent.

系统还必须能够解析一个模式实体。它的默认查询必须是 EntityStringQuery,或者该实体必须被索引。当 Xcode 提取 App Intents 元数据时,一个普通的 EntityQuery 会被拒绝。

🌐 The system must also be able to resolve a schema entity. Its default query must be an EntityStringQuery, or the entity must be indexed. Xcode rejects a plain EntityQuery when it extracts App Intents metadata.

原生 Swift 概念

🌐 Native Swift concepts

初始化器提供了可用的 Swift 示例,但意图声明属于你的应用。以下部分介绍了你用来调整示例或编写自己意图的主要原生组件。

🌐 The initializer provides working Swift examples, but the intent declarations belong to your app. The following sections describe the main native pieces you use to adapt the examples or write your own intents.

向 JavaScript 发送调用

🌐 Dispatch an invocation to JavaScript

一个意图的 perform() 方法会在 Swift 中生成 Siri 或快捷指令所期望的结果。调用 AppIntentDispatcher.shared.dispatch() 也可以记录 JavaScript 的调用:

🌐 An intent's perform() method produces the result Siri or Shortcuts expects in Swift. Call AppIntentDispatcher.shared.dispatch() to also record an invocation for JavaScript:

import AppIntents internal import ExpoAppIntents struct SaveNoteIntent: AppIntent { static let title: LocalizedStringResource = "Save Note" static let openAppWhenRun = true @Parameter(title: "Text") var text: String @MainActor func perform() async throws -> some IntentResult & ProvidesDialog { await AppIntentDispatcher.shared.dispatch( name: "saveNote", params: ["text": .string(text)] ) return .result(dialog: "Your note was saved.") } }

派发是单向的。它会保存调用并返回,而不等待 JavaScript,因为意图可能在你的应用关闭时运行。可以从 Swift 返回对话框、值或其他面向系统的结果。当 JavaScript 运行时,使用 JavaScript 处理器来更新你的应用状态。

🌐 Dispatching is one-way. It saves the invocation and returns without waiting for JavaScript because the intent may run while your app is closed. Return dialogs, values, or other system-facing results from Swift. Use the JavaScript handler to update your app's state when it runs.

params 接受与 JSON 兼容的 AppIntentValue 值:

Swift 值JavaScript 值
.string(String)string
.int(Int) 和 .double(Double)number
.bool(Bool)boolean
.array([AppIntentValue])数组
.object([String: AppIntentValue])对象
.nullnull

这个值类型也支持 Swift 字面量,所以你可以直接使用像 "note"、1、true、数组和字典这样的值。

🌐 The value type also supports Swift literals, so you can use values such as "note", 1, true, arrays, and dictionaries directly.

在 Swift 中读取动态实体

🌐 Read dynamic entities in Swift

使用 setEntityCatalogAsync() 从 JavaScript 发布当前实体值。你的 Swift EntityQuery 通过 AppIntentEntityStore.shared 读取相同的目录:

🌐 Publish current entity values from JavaScript with setEntityCatalogAsync(). Your Swift EntityQuery reads the same catalog through AppIntentEntityStore.shared:

struct NoteQuery: EntityStringQuery { func entities(for identifiers: [String]) async throws -> [NoteEntity] { return try await AppIntentEntityStore.shared .entities(ofKind: "note", matching: identifiers) .map(NoteEntity.init(record:)) } func suggestedEntities() async throws -> [NoteEntity] { return try await AppIntentEntityStore.shared .entities(ofKind: "note") .map(NoteEntity.init(record:)) } }

kind 字符串必须与传递给 setEntityCatalogAsync() 的值匹配。每个 AppIntentEntityRecord 都包含一个 id 和一个显示的 title。它还可以包含一个 subtitle 和 synonyms。在像 init(record:) 这样的初始化器中,将记录转换为具体的 AppEntity。设备存储目录,所以保持它们紧凑,只发布 Siri 和快捷指令需要的值。

🌐 The kind string must match the value passed to setEntityCatalogAsync(). Each AppIntentEntityRecord contains an id and a display title. It can also contain a subtitle and synonyms. Convert the record into your concrete AppEntity in an initializer such as init(record:). The device stores catalogs, so keep them compact and publish only the values Siri and Shortcuts need.

捐出一个意图

🌐 Donate an intent

捐赠告诉系统用户在你的应用中执行了某个意图的操作。系统会根据捐赠学习,并且以后可以在锁屏、Siri 建议和 Spotlight 中推荐该操作。只有 Swift 可以创建意图,所以让意图符合 DonatableAppIntent 并根据 JavaScript 传递的参数来构建它。将这些参数声明为带有 @Field 属性的 DonationParams 记录:

🌐 A donation tells the system that the user performed an intent's action inside your app. The system learns from donations and can suggest the action later on the Lock Screen, in Siri Suggestions, and in Spotlight. Only Swift can create an intent, so make the intent conform to DonatableAppIntent and build it from the parameters that JavaScript passes. Declare those parameters as a DonationParams record with @Field properties:

extension SaveNoteIntent: DonatableAppIntent { struct DonationParams: Record { @Field(.required) var text: String = "" } init(donationParams: DonationParams) { self.init() self.text = donationParams.text } }

在你的 AppIntentsSetup 模块的 OnCreate 中注册意图。JavaScript 会根据注册的名字来处理。它不要求必须与意图传给 dispatch() 的名字相匹配,但如果重用那个名字,每个意图在 JavaScript 中就会有一个名字:

🌐 Register the intent in the OnCreate of your AppIntentsSetup module. JavaScript donates by the registered name. Nothing requires it to match the name that the intent passes to dispatch(), but reusing that name gives each intent one name in JavaScript:

AppIntentDonationRegistry.shared.register("saveNote", as: SaveNoteIntent.self)

然后在用户在你的应用中保存注意后调用 donateIntentAsync()。当捐赠不再适用时调用 deleteDonationsAsync(),例如用户注销后:

🌐 Then call donateIntentAsync() after the user saves a note in your app. Call deleteDonationsAsync() when donations no longer apply, for example after the user signs out:

await AppIntents.donateIntentAsync('saveNote', { text: 'Buy milk' }); await AppIntents.deleteDonationsAsync({ intent: 'saveNote' });

当必填字段 DonationParams 缺失或某个字段类型错误时,捐赠会被拒绝。没有参数的意图只需要符合 DonatableAppIntent 就可以了。

🌐 The donation is rejected when a required field of DonationParams is missing or a field has the wrong type. An intent without parameters only needs to conform to DonatableAppIntent.

donateIntentAsync() 也会返回一个捐赠的 ID。把它传给 deleteDonationsAsync({ ids }) 就能只删除那次捐赠。

在需要时添加快捷短语

🌐 Add shortcut phrases when needed

当你想使用像“在 MyApp 中保存注意”这样的已编译启动短语时,请使用 AppShortcutsProvider。

🌐 Use an AppShortcutsProvider when you want compiled launch phrases such as "Save a note in MyApp".

用法

🌐 Usage

安装包之后,从你的项目根目录运行初始化程序:

🌐 After installing the package, run the initializer from your project root:

Terminal
- npx expo-app-intents init

该命令会添加配置插件,为顶层 app-intents 目录启用内联模块,并生成入门的 Swift 文件。

🌐 The command adds the config plugin, enables inline modules for the top-level app-intents directory, and writes starter Swift files.

该命令还会询问要包含哪些示例,并默认只选择 minimal。这个选项会在不包含意图、快捷短语或下面任何示例的情况下写入设置模块。传入 --examples 可以在不使用提示的情况下选择示例。这个标志也是在非交互式运行中唯一可以选择它们的方式:

🌐 The command also asks which examples to include and preselects only minimal. This option writes the setup module without intents, shortcut phrases, or any of the examples below. Pass --examples to choose examples without the prompt. This flag is also the only way to select them in a non-interactive run:

Terminal
- npx expo-app-intents init --examples counter restaurant mail

--examples 接受 minimal、counter、restaurant、mail 或 all。all 选项会选择本页描述的三个示例。当 CI 设置为 1 或 true,EXPO_NONINTERACTIVE 有值,或者标准输入不是交互式终端时,命令会以非交互方式运行。在这些情况下,命令会在不提示的情况下生成 minimal。

init 会保留已在所选目录中的任何 Swift 文件。如果你再次运行它以添加另一个示例,请在重建之前查看命令的警告。某些现有文件可能需要进行小幅手动更新。

传入 --dir 可以在 app-intents 以外的目录生成模块。初始化程序会将相同的目录名称写入配置插件和被监视的目录:

🌐 Pass --dir to generate the module in a directory other than app-intents. The initializer writes the same directory name to the config plugin and to the watched directories:

Terminal
- npx expo-app-intents init --dir siri

把 App Intents 目录放在项目根目录,就像默认的 app-intents 目录一样。这样位置可以让原生声明更容易找到,也能跟应用的其他部分分开。

🌐 Keep the App Intents directory at the project root, like the default app-intents directory. This location keeps the native declarations easy to find and separate from the rest of the app.

使用邮件示例传递 --visual-intelligence 来搭建其 Spotlight 集成。这会添加本地代码,使草稿可搜索,并让系统能够传输和打开草稿。它还会注册 mailDraft 实体类型,以便 appEntityIdentifier() 可以识别视图所表示的草稿。生成的代码会扩展基础邮件类型,因此无论是否使用此标志,示例都能以相同方式工作。

🌐 Pass --visual-intelligence with the mail example to scaffold its Spotlight integration. This adds native code that makes drafts searchable and lets the system transfer and open a draft. It also registers the mailDraft entity kind so appEntityIdentifier() can identify the draft represented by a view. The generated code extends the base mail types, so the example works the same way with or without this flag.

Terminal
- npx expo-app-intents init --examples mail --visual-intelligence

传入 --donations 来生成本地代码,使 JavaScript 能够捐赠选定示例的意图。这会为每个示例意图添加一个 DonatableAppIntent 扩展,并在 AppIntentsSetup.swift 中以它们分发的名称注册这些意图,例如 orderFood。在你选择示例后,交互式提示会询问相关内容。像 --visual-intelligence 一样,生成的代码会扩展基础类型,因此每个示例在有无该标志的情况下都能以相同方式工作。

🌐 Pass --donations to scaffold the native code that lets JavaScript donate the intents of the selected examples. This adds a DonatableAppIntent extension for each example intent and registers the intents in AppIntentsSetup.swift under the names they dispatch, such as orderFood. The interactive prompt asks about this after you pick the examples. Like --visual-intelligence, the generated code extends the base types, so each example works the same way with or without this flag.

Terminal
- npx expo-app-intents init --examples restaurant --donations

然后重建本地项目:

🌐 Then rebuild the native project:

Terminal
- npx expo prebuild -p ios
- npx expo run:ios

你的应用现在已经设置为使用应用意图。根据所选示例,你可以添加处理程序或从 JavaScript 填充应用意图:

🌐 Your app is now set up to use App Intents. Depending on the selected examples, you can add handlers or populate the App Intents from JavaScript:

将屏幕视图连接到实体

在 iOS 18.4 及更高版本中,appEntityIdentifier() 告诉 Siri @expo/ui SwiftUI 视图代表哪个实体,而 AppEntityView 对 React Native 视图也做同样的事情。这两者都要求项目使用 Xcode 27 或更高版本编译,因为它们使用的 Apple API 在早期的 SDK 中不可用。在本地注册、JavaScript 目录和视图中使用相同的实体类型和标识符。

🌐 On iOS 18.4 and later, appEntityIdentifier() tells Siri which entity an @expo/ui SwiftUI view represents, and AppEntityView does the same for React Native views. Both require the project to be compiled with Xcode 27 or later, because the Apple APIs they use are not available in earlier SDKs. Use the same entity kind and identifier in the native registration, JavaScript catalog, and view.

--visual-intelligence 邮件示例在 AppIntentsSetup.swift 中注册 mailDraft :

🌐 The --visual-intelligence mail example registers mailDraft in AppIntentsSetup.swift:

OnCreate { if #available(iOS 18.0, *) { AppEntityIdentifierRegistry.shared.registerIndexed( "mailDraft", as: MailDraftEntity.self ) } }

registerIndexed() 使标识符在屏幕智能中可用,并保持 Spotlight 与实体目录同步。自定义索引实体必须符合 IndexedEntity 和 AppIntentEntityRecordConvertible。如果想在不进行 Spotlight 索引的情况下支持屏幕智能,请改用 AppEntityIdentifierRegistry.shared.register() 注册该实体。

使用相同的 mailDraft 类型从 JavaScript 发布实体:

🌐 Publish the entity from JavaScript using the same mailDraft kind:

await AppIntents.setEntityCatalogAsync('mailDraft', [ { id: 'release-notes', title: 'Release notes for review', subtitle: 'The release notes are ready for a final pass.', }, ]);

然后将匹配的类型和标识符附加到一个 @expo/ui 视图上:

🌐 Then attach the matching kind and identifier to an @expo/ui view:

import { Column, Host, Text } from '@expo/ui'; import * as AppIntents from 'expo-app-intents'; export function MailDraftCard({ draft }: { draft: { id: string; subject: string } }) { return ( <Host matchContents={{ vertical: true }}> <Column modifiers={[AppIntents.appEntityIdentifier('mailDraft', draft.id)]}> <Text>{draft.subject}</Text> </Column> </Host> ); }

要标记 React Native 视图,请将它们封装在具有相同类型和标识符的 AppEntityView 中:

🌐 To mark React Native views instead, wrap them in AppEntityView with the same kind and identifier:

import { Text } from 'react-native'; import * as AppIntents from 'expo-app-intents'; export function MailDraftCard({ draft }: { draft: { id: string; subject: string } }) { return ( <AppIntents.AppEntityView entity="mailDraft" entityId={draft.id}> <Text>{draft.subject}</Text> </AppIntents.AppEntityView> ); }

在早期 iOS 版本上,这两种视图仍然可以正常显示,或者在使用 Xcode 27 之前的版本编译的项目中,或者当这种类型未注册时也是如此。在这些情况下,系统无法将视图与实体关联,并且 expo-app-intents 会记录一次警告。

🌐 Both views still render normally on earlier iOS versions, in a project compiled with an Xcode version earlier than 27, or when the kind is not registered. In these cases, the system cannot associate the view with the entity, and expo-app-intents logs a warning once.

处理反例

这个反例会派发一个 increaseCounter 调用。在应用的根部附近只安装一次钩子。然后它可以处理在 JavaScript 未运行时捕获的待处理调用,以及应用运行时收到的实时调用。

🌐 The counter example dispatches an increaseCounter invocation. Mount the hook once near the root of your app. It can then process pending invocations captured while JavaScript was not running and live invocations received while the app is running.

投递至少一次,所以同一个调用可能会多次到达你的处理器。调用会一直在待处理队列中,直到 removePendingInvocationAsync(id) 成功完成。每个活跃调用都会提供该队列的新快照。

🌐 Delivery is at-least-once, so the same invocation can reach your handler more than once. An invocation stays in the pending queue until removePendingInvocationAsync(id) completes successfully. Each live invocation delivers a fresh snapshot of that queue.

把你已经使用过的调用标识保存在一个 ref 里,然后跳过它们。餐厅和邮件的示例使用了相同的保护。一个 ref 只会在一次会话内去重调用。如果 removePendingInvocationAsync() 失败,下次启动时调用仍然挂起,你的处理器会再次应用它。当你无法安全地重复执行一个操作时,需要保存已经处理过的标识。队列最多保存 100 个调用,老的会被删掉以腾出空间。一个从不删除调用的应用最终会丢失它们。

🌐 Keep the identifiers of invocations you have already applied in a ref and skip them. The restaurant and mail examples use the same guard. A ref deduplicates invocations only within one session. If removePendingInvocationAsync() fails, the invocation remains pending on the next launch and your handler applies it again. Persist the handled identifiers when you cannot safely reapply an action. The queue holds at most 100 invocations and drops the oldest to make room. An app that never removes invocations eventually loses them.

import { useRef, useState } from 'react'; import { Text, View } from 'react-native'; import * as AppIntents from 'expo-app-intents'; export function CounterIntentHandler() { const [count, setCount] = useState(0); const [lastIntentId, setLastIntentId] = useState<string | null>(null); const handledIds = useRef(new Set<string>()); AppIntents.useAppIntents(async pendingIntents => { for (const invocation of pendingIntents) { if (invocation.name !== 'increaseCounter' || handledIds.current.has(invocation.id)) { continue; } handledIds.current.add(invocation.id); setCount(value => value + 1); setLastIntentId(invocation.id); await AppIntents.removePendingInvocationAsync(invocation.id); } }); return ( <View> <Text>Counter: {count}</Text> {lastIntentId ? <Text>Last opened by Siri: {lastIntentId}</Text> : null} </View> ); }
处理餐厅的例子

餐厅示例使用了一个动态的 dish 实体目录。在应用启动后,通过 JavaScript 初始化目录,然后处理 orderFood 调用。调用 setEntityCatalogAsync() 会替换原生目录并刷新快捷方式参数。Siri 和快捷指令随后可以通过标识符、标题或同义词来识别菜品。处理被拒绝的 Promise,这样目录更新失败时会在日志中显示,而不会变成未处理的拒绝。

🌐 The restaurant example uses a dynamic dish entity catalog. Seed the catalog from JavaScript after the app starts, and then handle orderFood invocations. Calling setEntityCatalogAsync() replaces the native catalog and refreshes shortcut parameters. Siri and Shortcuts can then resolve dishes by identifier, title, or synonym. Handle a rejected promise so a failed catalog update appears in your logs instead of becoming an unhandled rejection.

import { useEffect, useRef, useState } from 'react'; import { Text, View } from 'react-native'; import * as AppIntents from 'expo-app-intents'; const dishes = [ { id: 'margherita-pizza', title: 'Margherita Pizza', synonyms: ['margherita', 'pizza'] }, { id: 'spaghetti-carbonara', title: 'Spaghetti Carbonara', synonyms: ['carbonara'] }, { id: 'tiramisu', title: 'Tiramisu', synonyms: ['dessert'] }, ]; export function RestaurantIntentHandler() { const [latestOrder, setLatestOrder] = useState<string | null>(null); const handledIds = useRef(new Set<string>()); useEffect(() => { AppIntents.setEntityCatalogAsync('dish', dishes).catch(error => console.warn('Could not publish the dish catalog.', error) ); }, []); AppIntents.useAppIntents(async pendingIntents => { for (const invocation of pendingIntents) { if (invocation.name !== 'orderFood' || handledIds.current.has(invocation.id)) { continue; } handledIds.current.add(invocation.id); setLatestOrder(String(invocation.params.dishName || invocation.params.dishId)); await AppIntents.removePendingInvocationAsync(invocation.id); } }); return ( <View> <Text>{latestOrder ? `Latest order: ${latestOrder}` : 'No orders yet.'}</Text> </View> ); }
处理邮件示例

该邮件示例采用苹果的 mail 架构域,并且没有快捷短语。你可以通过 Siri、苹果智能或快捷指令应用访问这两个意图。createMailDraft 会发送 id、subject、body、recipients 和 attachmentCount。deleteMailDrafts 会发送一个 ids 数组。由于删除是破坏性的操作,该架构要求本地设备认证,并在意图运行前显示确认。

🌐 The mail example adopts Apple's mail schema domain and has no shortcut phrases. You can reach both intents through Siri, Apple Intelligence, or the Shortcuts app. createMailDraft sends id, subject, body, recipients, and attachmentCount. deleteMailDrafts sends an ids array. Because deleting is destructive, the schema requires local device authentication and displays a confirmation before the intent runs.

DeleteDraftIntent 接受一个 MailDraftEntity 值的数组,所以一次调用可以删除多个草稿。MailDraftEntityQuery 从 mailDraft 目录中解析这些实体。每当你的草稿发生变化时,发布目录。否则,Siri 和快捷指令应用无法提供草稿,删除意图也无法执行。每条记录将 title 映射到主题,subtitle 映射到正文。原生存储可以在重启后保留目录,所以在草稿加载前不要发布空目录。

给每条记录一个非空的 title。当任何实体的 id 或 title 为空时,setEntityCatalogAsync() 会拒绝目录,因为 Siri 无法解析该实体。拒绝会丢弃整个更新,并保留之前的目录。创建草稿而没有主题时,会提供一个空的 subject 字符串,而不是 undefined。使用 || 作为回退,而不是 ??,因为 ?? 会保留空字符串。

🌐 Give every record a non-empty title. setEntityCatalogAsync() rejects a catalog when any entity has an empty id or title because Siri cannot resolve the entity. The rejection discards the entire update and keeps the previous catalog. A draft created without a subject provides an empty subject string instead of undefined. Use || instead of ?? for the fallback because ?? preserves the empty string.

import { useEffect, useRef, useState } from 'react'; import { FlatList, Text } from 'react-native'; import * as AppIntents from 'expo-app-intents'; type MailDraft = { id: string; subject: string; body: string; }; export function MailIntentHandler() { const [drafts, setDrafts] = useState<MailDraft[]>([]); const handledIds = useRef(new Set<string>()); const hasPublished = useRef(false); useEffect(() => { // The native catalog outlives the app, but `drafts` starts empty, so publishing on the // first render would clear a catalog written by an earlier launch. Wait for a draft. if (drafts.length === 0 && !hasPublished.current) { return; } hasPublished.current = true; AppIntents.setEntityCatalogAsync( 'mailDraft', drafts.map(draft => ({ id: draft.id, title: draft.subject, subtitle: draft.body })) ).catch(error => console.warn('Could not publish the mail draft catalog.', error)); }, [drafts]); AppIntents.useAppIntents(async pendingIntents => { for (const invocation of pendingIntents) { const isMailIntent = invocation.name === 'createMailDraft' || invocation.name === 'deleteMailDrafts'; if (!isMailIntent || handledIds.current.has(invocation.id)) { continue; } handledIds.current.add(invocation.id); if (invocation.name === 'createMailDraft') { const body = String(invocation.params.body ?? ''); const draft = { id: String(invocation.params.id || invocation.id), // Use `||`, not `??`: a draft with no subject arrives as an empty string. subject: String(invocation.params.subject || body.slice(0, 40) || 'No subject'), body, }; setDrafts(current => [draft, ...current]); } else { const ids = new Set((invocation.params.ids as string[] | undefined) ?? []); setDrafts(current => current.filter(draft => !ids.has(draft.id))); } await AppIntents.removePendingInvocationAsync(invocation.id); } }); return ( <FlatList data={drafts} keyExtractor={draft => draft.id} renderItem={({ item }) => ( <Text> {item.subject}: {item.body} </Text> )} /> ); }
Basic example
import * as AppIntents from 'expo-app-intents'; export function AppIntentHandler() { AppIntents.useAppIntents(async (pendingIntents, newIntent) => { for (const invocation of pendingIntents) { switch (invocation.name) { case 'increaseCounter': console.log('Increase counter:', invocation.id === newIntent?.id); break; case 'orderFood': console.log('Dish:', invocation.params.dishName, invocation.id === newIntent?.id); break; } await AppIntents.removePendingInvocationAsync(invocation.id); } }); return null; }

从 JavaScript 为参数化意图提供动态值:

🌐 Provide dynamic values for parameterized intents from JavaScript:

await AppIntents.setEntityCatalogAsync('dish', [ { id: 'margherita-pizza', title: 'Margherita Pizza', synonyms: ['margherita', 'pizza'] }, { id: 'spaghetti-carbonara', title: 'Spaghetti Carbonara', synonyms: ['carbonara'] }, ]);

生成的实体查询通过 await AppIntentEntityStore.shared.entities(ofKind:) 读取这些值。Siri 和快捷指令随后可以将它们作为意图参数提供和解析。

🌐 The generated entity queries read these values through await AppIntentEntityStore.shared.entities(ofKind:). Siri and Shortcuts can then offer and resolve them as intent parameters.

在一个实体上设置 hideInSpotlight 可以让它不出现在 Spotlight 索引中,同时仍然可以被解析。Siri 仍然可以将其作为参数提供,并通过标识符打开它:

🌐 Set hideInSpotlight on an entity to keep it out of the Spotlight index while leaving it resolvable. Siri can still offer it as a parameter and open it by identifier:

await AppIntents.setEntityCatalogAsync('mailDraft', [ { id: 'release-notes', title: 'Release notes for review' }, { id: 'salary-review', title: 'Salary review', hideInSpotlight: true }, ]);

这个标志只适用于原生注册到 registerIndexed 的实体。翻转它将在下次目录发布时生效,而且已经被索引的实体会被移除。要想完全让某个实体不出现在 Siri 中,直接不要把它放进目录。未发布的实体无法被提供、匹配或解析。

🌐 The flag only applies to entities registered natively with registerIndexed. Flipping it takes effect the next time the catalog is published, and an entity that was already indexed is removed. To keep an entity away from Siri altogether, leave it out of the catalog instead. An entity that isn't published can't be offered, matched, or resolved.

Classic App 快捷短语最多只能插入一个非数组参数。生成的餐厅点餐示例声明了四个短语:

🌐 Classic App Shortcut phrases can interpolate at most one non-array parameter. The generated restaurant order example declares four phrases:

"Place an order in \(.applicationName)", "Order food in \(.applicationName)", "Order \(\.$dish) in \(.applicationName)", "Place an order for \(\.$dish) in \(.applicationName)"

前两个短语没有插入参数,所以 Siri 会问你想要哪道菜。后两个则插入了 dish 参数。这个参数让 Siri 可以执行一次性命令,比如“在 MyApp 里点Tiramisu”。带参数的短语可以在快捷指令里生成预填充的按钮。如果一个旧版本生成的按钮使用了过时的参数值,删掉它,iOS 就能根据当前的应用元数据重新创建。

🌐 The first two phrases do not interpolate a parameter, so Siri asks which dish you want. The last two interpolate the dish parameter. This parameter lets Siri run a one-shot command such as "Order Tiramisu in MyApp". Parameterized phrases can create pre-filled tiles in Shortcuts. If an older build created a tile that uses stale parameter values, delete it so iOS can recreate it from the current app metadata.

平台限制

🌐 Platform constraints

  • 本地运行时支持 iOS 16.4 及更高版本、tvOS 16.4 及更高版本以及 macOS 13.4 及更高版本。expo-app-intents 在 Expo Go 中不可用。
  • 本页的初始化器、示例包和构建命令主要针对 iOS。某些单独的应用意图 API 和架构域可能需要更新的操作系统版本,或者在其他 Apple 平台上不可用。
  • 应用快捷短语是预先编译到应用里的,不能通过 JavaScript 动态添加。
  • 每个应用快捷方式短语都必须包含 \(.applicationName)。
  • 一个 App 快捷方式短语最多只能插入一个非数组参数。
  • 应用最多可以定义 10 个应用快捷方式。
  • 模式示例需要 iOS 18 或更高版本,并且必须匹配 Apple 的 支持的 App Intent 域 之一。只有主要域才能被 Apple 智能和 Siri 发现。
  • 有些模式需要比它们所属域更新的 iOS 版本。例如,.mail.openDraft 和 .system.open 需要 iOS 27 或更高版本。

其他资源

🌐 Additional resources

从 npx expo-app-intents init 生成的反例开始。它展示了 JavaScript 和 Swift 运行时之间的基本连接。然后使用餐厅和邮件的例子来了解动态实体和模式意图。

🌐 Start with the counter example generated by npx expo-app-intents init. It demonstrates the basic connection between the JavaScript and Swift runtimes. Then use the restaurant and mail examples to learn about dynamic entities and schema intents.

使用以下 Apple 资源来更多了解 App Intent 开发:

🌐 Use the following Apple resources to learn more about App Intent development:

应用接口

🌐 API

import * as AppIntents from 'expo-app-intents';

No API data file found, sorry!