--- url: /zh/guide/AppIntent.md --- # AppIntent `AppIntentManager` 用于在 **Scripting** 中注册并管理 `AppIntent`,它是 Widget、Live Activity、ControlWidget 等控件执行脚本逻辑的核心机制。 所有的 `AppIntent` **必须** 定义在 `app_intents.tsx` 文件中,且在执行时其运行环境 `Script.env` 为 `"app_intents"`。 通过 `AppIntentManager` 注册的意图可以被 Widget / Live Activity / ControlWidget 中的 **Button** 与 **Toggle** 控件调用,以在用户交互时触发对应的脚本逻辑。 *** ## 一、类型定义 ### `AppIntent` 表示一个具体的应用意图实例。 | 字段名 | 类型 | 描述 | | ---------- | ------------------- | ---------------------------------------- | | `script` | `string` | 脚本路径,由系统内部生成。 | | `name` | `string` | 意图名称,唯一标识该 AppIntent。 | | `protocol` | `AppIntentProtocol` | 该意图实现的协议类型(如普通、音频播放、音频录制、Live Activity)。 | | `params` | `T` | 意图执行时的参数。 | *** ### `AppIntentFactory` 表示一个 **工厂函数**,用于通过参数创建 `AppIntent` 实例。 ```ts type AppIntentFactory = (params: T) => AppIntent ``` *** ### `AppIntentPerform` 表示一个执行函数,用于在意图被触发时执行实际逻辑。 ```ts type AppIntentPerform = (params: T) => Promise ``` *** ### `AppIntentProtocol` `AppIntentProtocol` 是枚举类型,用于指定意图的协议(行为类别)。 | 枚举成员 | 描述 | | -------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `AppIntent` (0) | 普通 AppIntent。用于执行一般操作的意图。 | | `AudioPlaybackIntent` (1) | 播放、暂停或修改音频播放状态的意图。 | | `AudioRecordingIntent` (2) | (iOS 18.0+)启动、停止或修改音频录制状态的意图。**注意**:在 iOS/iPadOS 中,当使用 `AudioRecordingIntent` 协议时,必须在开始录音时启动一个 **Live Activity** 并在录音持续时保持活跃,否则音频录制将会停止。 | | `LiveActivityIntent` (3) | 启动、暂停或修改 Live Activity 的意图。 | *** ## 二、AppIntentManager 类 ### `AppIntentManager.register(options): AppIntentFactory` 注册一个新的 `AppIntent`。 通过指定 `name`、`protocol` 和 `perform` 函数来注册,当控件(Button/Toggle)被触发时,系统会自动调用 `perform` 函数执行逻辑。 ```ts static register(options: { name: string; protocol: AppIntentProtocol; perform: AppIntentPerform; }): AppIntentFactory ``` #### 参数: | 参数名 | 类型 | 描述 | | ---------- | --------------------- | ------------------------------------- | | `name` | `string` | AppIntent 的名称,需唯一,用于标识该意图。 | | `protocol` | `AppIntentProtocol` | AppIntent 的协议类型。 | | `perform` | `AppIntentPerform` | 当控件触发该意图时执行的异步函数,参数为控件传递过来的 `params`。 | #### 返回值: - **`AppIntentFactory`**:返回一个工厂函数,可通过传入参数创建 `AppIntent` 实例。 #### 示例: ```tsx /// app_intents.tsx export const ToggleDoorIntent = AppIntentManager.register({ name: "ToggleDoorIntent", protocol: AppIntentProtocol.AppIntent, perform: async ({ id, newState }: { id: string; newState: boolean }) => { // 自定义逻辑:切换门的状态 await setDoorState(id, newState) // 通知控件刷新状态(如 ControlWidgetToggle) ControlWidget.reloadToggles() } }) ``` 在控件文件中(如 `control_widget_toggle.tsx`): ```tsx ControlWidget.present( ) ``` 在小组件中使用(如 `widget.tsx`): ```tsx ``` *** ## 三、执行时环境 所有通过 `AppIntentManager` 定义的 AppIntent 在执行时,`Script.env` 会自动为 `"app_intents"`。 这意味着在 `perform` 函数中可以安全地使用适合 `"app_intents"` 环境的 API(如访问网络、更新 Live Activity 状态、触发控件刷新等)。 *** ## 四、最佳实践 1. **集中管理**:所有 AppIntent 必须定义在 `app_intents.tsx` 文件中,避免分散。 2. **类型安全**:在 `perform` 和控件参数中定义严格的参数类型 `T`,以确保开发时的自动补全与类型检查。 3. **协议匹配**:根据控件行为选择合适的 `AppIntentProtocol`,例如: - 普通操作 → `AppIntent` - 控制音频播放 → `AudioPlaybackIntent` - 控制音频录制 → `AudioRecordingIntent`(iOS 18+ 且需保持 Live Activity) - 启动/暂停 Live Activity → `LiveActivityIntent` 4. **状态刷新**:执行完 `perform` 后,如需更新 UI 状态(例如切换门锁开关),请调用 `ControlWidget.reloadButtons()` 、 `ControlWidget.reloadToggles()` 或 `Widget.reloadAll()`。 --- url: /zh/guide/Assistant/Assistant Conversation APIs.md --- # 智能助手会话 API Conversation API 用于**启动、控制和展示一个由系统托管的 Assistant 对话会话**。 该会话对应一个**完整的聊天页面(Chat Page)**,由 Scripting App 统一管理 UI、状态和模型交互。 与 `requestStreaming` / `requestStructuredData` 的区别在于: - Conversation API 面向**交互式聊天体验** - 系统负责消息发送、流式输出、Provider 切换、UI 渲染 - 开发者只需关注“何时开始 / 何时结束 / 是否展示” *** ## 会话生命周期概览 一个典型的会话生命周期如下: 1. `startConversation` —— 创建会话(可选自动开始) 2. `present` —— 展示 Assistant 聊天页面 3. 用户与 Assistant 进行交互 4. `dismiss` —— 临时关闭聊天页面(会话仍存在) 5. `present` —— 再次展示会话 6. `stopConversation` —— 结束会话并释放资源 重要约束: - **同一时间只能存在一个活动会话** - 若已有会话在运行,再次调用 `startConversation` 会抛出错误 - 调用 `stopConversation` 会自动触发 `dismiss` *** ## startConversation ### API 定义 ```ts function startConversation(options: { message: string images?: UIImage[] autoStart?: boolean systemPrompt?: string modelId?: string provider?: Provider providerID?: string }): Promise ``` *** ### 参数说明 #### options.message - 类型:`string` - 必填 - 会话的**初始用户消息** - 相当于聊天页面中的第一条用户输入 *** #### options.images(可选) - 类型:`UIImage[]` - 会与 `message` 一起作为首条用户消息发送 - 适用于: - 图片分析 - 拍照 / 截图后直接发起对话 *** #### options.autoStart(可选) - 类型:`boolean` - 默认值:`false` 行为说明: - `true`: - 创建会话后立即开始生成回复 - `false`: - 仅创建会话,不自动发送 - 通常配合 `present` 使用,由用户点击发送 *** #### options.systemPrompt(可选) - 类型:`string` 说明: - 若未提供: - 使用 Scripting Assistant 内置 system prompt - Assistant Tools 可用 - 若提供: - 完全替换默认 system prompt - **Assistant Tools 将不可用** 适用场景: - 构建高度定制的聊天角色 - 禁用工具调用,仅使用纯模型能力 *** #### options.modelId(可选) - 类型:`string` - 指定本次会话使用的模型 - 用户仍可在聊天页面中手动切换模型(若 UI 允许) *** #### options.provider(可选) - 类型:`Provider` - 指定默认 Provider - 用户可在聊天页面中更改 Provider(若 UI 允许) *** ### 返回值 ```ts Promise ``` - 会话创建成功即 resolve - 若已有会话存在,将 reject *** ## present ### API 定义 ```ts function present(): Promise ``` *** ### 行为说明 - 展示当前会话对应的 Assistant 聊天页面 - 若页面已展示,调用不会产生额外效果 - 可在以下场景调用: - `startConversation` 之后首次展示 - `dismiss` 后重新展示同一会话 *** ### 返回值 ```ts Promise ``` - 当聊天页面被用户关闭时 resolve *** ## dismiss ### API 定义 ```ts function dismiss(): Promise ``` *** ### 行为说明 - 关闭 Assistant 聊天页面 - **不会终止会话** - 会话状态、历史消息仍保留 适用场景: - 临时让出界面空间 - 页面跳转或多任务切换 *** ### 返回值 ```ts Promise ``` - 页面成功关闭后 resolve *** ## stopConversation ### API 定义 ```ts function stopConversation(): Promise ``` *** ### 行为说明 - 彻底终止当前会话 - 自动调用 `dismiss` - 清理会话状态与资源 - 结束后可再次调用 `startConversation` 创建新会话 *** ### 返回值 ```ts Promise ``` *** ## 会话状态相关常量 ### Assistant.isAvailable ```ts const isAvailable: boolean ``` - 表示当前用户是否**具备使用 Assistant 的权限** - 若为 `false`: - 所有 Conversation API 均不可用 *** ### Assistant.isPresented ```ts const isPresented: boolean ``` - 表示 Assistant 聊天页面当前是否处于展示状态 *** ### Assistant.hasActiveConversation ```ts const hasActiveConversation: boolean ``` - 表示当前是否存在一个活动会话 - 常用于防止重复调用 `startConversation` *** ## 使用示例 ### 示例一:最常见的使用方式 ```ts await Assistant.startConversation({ message: "帮我总结这篇文章的要点", autoStart: true }) await Assistant.present() ``` *** ### 示例二:创建会话但不自动发送 ```ts await Assistant.startConversation({ message: "我们来讨论一下系统架构设计", autoStart: false }) await Assistant.present() // 由用户在 UI 中手动点击发送 ``` *** ### 示例三:暂时关闭,再次展示 ```ts await Assistant.startConversation({ message: "分析这张图片", images: [image], autoStart: true }) await Assistant.present() // 用户关闭页面 await Assistant.dismiss() // 稍后再次展示同一会话 await Assistant.present() ``` *** ### 示例四:结束当前会话并重新开始 ```ts if (Assistant.hasActiveConversation) { await Assistant.stopConversation() } await Assistant.startConversation({ message: "开始一个新的话题", autoStart: true }) await Assistant.present() ``` *** ## 使用建议与最佳实践 - 将 Conversation API 视为“**托管聊天界面**” - 不要在同一业务流中混用 Conversation API 与 `requestStreaming` - 在调用 `startConversation` 前检查 `hasActiveConversation` - 若仅需要数据或一次性输出,应使用: - `requestStructuredData` - `requestStreaming` - 若用户需要持续交互体验,应使用 Conversation API *** ## 设计边界说明 - Conversation API 不适合无 UI 场景 - 不适合后台自动化任务 - 不适合需要完全控制 Prompt / Token / 输出格式的场景 ### 精确选择账号 在 options 中传入 `providerID`,可按稳定 ID 选择一个已配置账号;可以不传 `provider`,同时传入时必须匹配。未知或已删除的 ID 会报错,不会换号。通过 `await Assistant.getProviders()` 获取 ID 和模型信息,或在 Provider 面板复制 ID。仅传旧内置 `provider` 类型时,会选择该类型持久列表中的首个已配置账号。发现与模型选择器示例见 Assistant 总览。 --- url: /zh/guide/Assistant/Assistant Quick Start.md --- # 快速了解智能助手 Scripting 的 Assistant API 提供了三类能力,分别面向 **数据处理**、**流式输出** 和 **交互式聊天** 三种不同使用场景。 在使用之前,建议先明确你的需求属于哪一类。 *** ## Assistant API 分类总览 | API 分类 | 主要方法 | 适用场景 | | ------ | ---------------------------------------------------------------- | ---------------------- | | 结构化数据 | `requestStructuredData` | 从文本 / 图片中提取结构化 JSON 数据 | | 流式生成 | `requestStreaming` | 实时展示 AI 输出内容 | | 会话聊天 | `startConversation` / `present` / `dismiss` / `stopConversation` | 托管式聊天体验 | *** ## requestStructuredData **用途** 用于请求**严格符合 JSON Schema 的结构化结果**。 **适合场景** - 解析票据、发票、账单 - 从自然语言中提取字段 - 生成配置、规则、表单数据 - 需要直接用于程序逻辑的数据 **特点** - 返回值稳定、可预测 - 不适合长文本或展示型输出 - 适合后台或无 UI 场景 **一句话总结** > 需要“数据”,用 `requestStructuredData` *** ## requestStreaming **用途** 用于获取**流式输出**,在模型生成过程中持续接收内容。 **适合场景** - 聊天气泡逐字显示 - 长文本生成(文章、说明、分析) - 需要低延迟反馈的 UI **特点** - 支持文本、推理、用量等多种 Chunk - 可边生成边渲染 - 不保证输出结构 **一句话总结** > 需要“过程”和“实时展示”,用 `requestStreaming` *** ## Conversation API(会话聊天) **相关方法** - `startConversation` - `present` - `dismiss` - `stopConversation` **用途** 用于创建并展示一个**系统托管的 Assistant 聊天页面**。 **适合场景** - 类 ChatGPT 的交互体验 - 用户需要多轮对话 - 希望系统管理 UI、Provider 切换、消息状态 **特点** - 内置完整聊天 UI - 自动处理流式输出 - 同一时间仅支持一个会话 **一句话总结** > 需要“完整聊天体验”,用 Conversation API *** ## 如何选择合适的 API ### 常见选择指南 - **我要解析一张账单 →** `requestStructuredData` - **我要展示 AI 写文章的过程 →** `requestStreaming` - **我要打开一个聊天页面让用户和 AI 对话 →** Conversation API - **我不需要 UI,只要结果 →** `requestStructuredData` 或 `requestStreaming` - **我希望系统帮我处理聊天 UI →** Conversation API *** ## 简单示例 ### 结构化数据 ```ts const data = await Assistant.requestStructuredData(...) ``` *** ### 流式输出 ```ts const stream = await Assistant.requestStreaming(...) for await (const chunk of stream) { // handle chunk } ``` *** ### 聊天会话 ```ts await Assistant.startConversation({ message: "你好", autoStart: true }) await Assistant.present() ``` *** ## 使用建议 - 不要在同一业务流程中混用 Conversation API 和 `requestStreaming` - 有明确数据结构需求时,优先选择 `requestStructuredData` - 展示型输出和交互体验优先考虑 `requestStreaming` 或 Conversation API *** ## 下一步 如果你需要更深入的内容,可以继续阅读: - `requestStructuredData` 详细文档 - `requestStreaming` 详细文档 - Conversation API 生命周期说明 --- url: /zh/guide/Assistant/requestStreaming.md --- # 请求流式数据 `requestStreaming` 用于向 Assistant 请求**流式输出(Streaming Response)**。 与一次性返回完整结果不同,该 API 会在模型生成内容的过程中**持续返回数据片段(Chunk)**,调用方可以边接收边处理,从而实现: - 实时展示 AI 输出(打字机效果) - 流式日志 / 分段结果处理 - 长文本生成的低延迟体验 - 在生成过程中提前终止或切换 UI 状态 该 API 返回的是一个 **`ReadableStream`**,你可以通过 `for await ... of` 逐块读取。 *** ## API 定义 ```ts function requestStreaming(options: { systemPrompt?: string | null messages: MessageItem | MessageItem[] provider?: Provider providerID?: string modelId?: string }): Promise> ``` *** ## 参数说明 ### options.systemPrompt(可选) - 类型:`string | null` - 指定本次请求使用的 system prompt - 若未提供: - 使用 Assistant 内置的默认 system prompt - 若显式传入: - 将**完全替换默认 system prompt** - Assistant Tools 将**不可用** 适用场景: - 构建专用角色(如代码审查、翻译、摘要) - 严格约束模型行为或输出风格 *** ### options.messages - 类型:`MessageItem | MessageItem[]` - 必填 - 用于描述对话上下文的消息列表 #### MessageItem 结构 ```ts type MessageItem = { role: "user" | "assistant" content: MessageContent | MessageContent[] } ``` - `role` - `"user"`:用户输入 - `"assistant"`:历史 Assistant 输出(用于上下文补全) *** ### MessageContent 类型 #### 文本内容 ```ts type MessageTextContent = | string | { type: "text"; content: string } ``` *** #### 图片内容 ```ts type MessageImageContent = { type: "image" content: string // data:image/...;base64,... } ``` *** #### 文档内容 ```ts type MessageDocumentContent = { type: "document" content: { mediaType: string data: string // base64 } } ``` *** ### options.provider(可选) - 类型:`Provider` - 指定使用的 AI Provider - 若未指定: - 使用 Assistant 当前配置的默认 Provider - 支持: - `"openai"` - `"gemini"` - `"anthropic"` - `"deepseek"` - `"openrouter"` - `{ custom: string }` *** ### options.modelId(可选) - 类型:`string` - 指定具体模型 ID - 必须与 Provider 实际支持的模型匹配 - 若未指定,使用 Provider 默认模型 *** ## 返回值 ```ts Promise> ``` 该 Promise resolve 后,你将获得一个可异步迭代的流对象。 *** ## StreamChunk 类型说明 `requestStreaming` 的流中会返回以下三类 Chunk。 *** ### StreamTextChunk(文本输出) ```ts type StreamTextChunk = { type: "text" content: string } ``` - 表示 Assistant 生成的**可展示文本** - 多个 chunk 拼接后构成完整回复 *** ### StreamReasoningChunk(推理输出) ```ts type StreamReasoningChunk = { type: "reasoning" content: string } ``` - 表示模型的**中间推理过程** - 是否返回、返回粒度取决于 Provider / Model *** ### StreamUsageChunk(用量信息) ```ts type StreamUsageChunk = { type: "usage" content: { totalCost: number | null cacheReadTokens: number | null cacheWriteTokens: number | null inputTokens: number outputTokens: number } } ``` 说明: - 通常在流的**末尾**返回一次 - 不同 Provider 支持的字段略有差异 - `totalCost` 可能为 `null`(例如 Provider 未提供费用信息) *** ## 使用示例 ### 示例一:最基本的流式请求 ```ts const stream = await Assistant.requestStreaming({ messages: { role: "user", content: "给我讲一个简短的科幻故事" }, provider: "openai" }) let text = "" for await (const chunk of stream) { if (chunk.type === "text") { text += chunk.content console.log(chunk.content) } } ``` *** ### 示例二:区分文本、推理和用量 ```ts const stream = await Assistant.requestStreaming({ systemPrompt: "你是一个严谨的技术写作助手", messages: [ { role: "user", content: "解释什么是 HTTP/3" } ] }) let answer = "" let reasoningLog = null let usage = null for await (const chunk of stream) { switch (chunk.type) { case "text": answer += chunk.content break case "reasoning": reasoningLog = (reasoningLog ?? "") + chunk.content break case "usage": usage = chunk.content break } } console.log(answer) console.log(usage) ``` *** ### 示例三:包含图片与文档的流式请求 ```ts const stream = await Assistant.requestStreaming({ messages: [ { role: "user", content: [ { type: "text", content: "请分析这份文档的核心内容" }, { type: "document", content: { mediaType: "application/pdf", data: "JVBERi0xLjQKJcfs..." } } ] } ], provider: "anthropic" }) for await (const chunk of stream) { if (chunk.type === "text") { console.log(chunk.content) } } ``` *** ## 使用建议与注意事项 - 流式结果**必须按顺序消费**,不可并发读取 - UI 场景下建议: - 文本 chunk 实时渲染 - reasoning chunk 仅用于调试 - usage chunk 延迟处理 - 若中途不再需要结果,应主动中止读取,避免无意义消耗 - 并非所有 Provider / Model 都会返回 reasoning 或 usage - 不同 Provider 的 chunk 粒度不同,不应假设单次 chunk 是完整句子 ### 精确选择账号 在 options 中传入 `providerID`,可按稳定 ID 选择一个已配置账号;可以不传 `provider`,同时传入时必须匹配。未知或已删除的 ID 会报错,不会换号。通过 `await Assistant.getProviders()` 获取 ID 和模型信息,或在 Provider 面板复制 ID。仅传旧内置 `provider` 类型时,会选择该类型持久列表中的首个已配置账号。发现与模型选择器示例见 Assistant 总览。 --- url: /zh/guide/Assistant/requestStructuredData.md --- # 请求结构化数据 `requestStructuredData` 用于向 Assistant 请求**严格符合指定 JSON Schema 的结构化 JSON 数据**。 该 API 适合在你需要**可预测、可直接用于程序逻辑**的数据结果时使用,而不是自由文本。 典型使用场景包括: - 从自然语言中提取结构化字段 - 解析发票、收据、账单、票据 - 生成配置对象、规则数据 - 在不同 AI Provider / Model 之间获得一致的数据结构 *** ## 支持的 JSON Schema 类型 Scripting 提供了一套轻量级、跨模型可用的 Schema 描述方式,由三种基础类型组成。 ### Primitive(基础类型) ```ts type JSONSchemaPrimitive = { type: "string" | "number" | "boolean" required?: boolean description: string } ``` *** ### Object(对象类型) ```ts type JSONSchemaObject = { type: "object" properties: Record required?: boolean description: string } ``` *** ### Array(数组类型) ```ts type JSONSchemaArray = { type: "array" items: JSONSchemaType required?: boolean description: string } ``` *** ## API 定义 ### 不包含图片输入 ```ts function requestStructuredData( prompt: string, schema: JSONSchemaArray | JSONSchemaObject, options?: { provider?: Provider providerID?: string modelId?: string } ): Promise ``` *** ### 包含图片输入 ```ts function requestStructuredData( prompt: string, images: string[], schema: JSONSchemaArray | JSONSchemaObject, options?: { provider?: Provider providerID?: string modelId?: string } ): Promise ``` *** ## 参数说明 ### prompt - 类型:`string` - 必填 - 向模型说明**需要解析或生成什么结构化数据** - 强烈建议在 prompt 中明确: - 时间格式(如 ISO-8601) - 金额是否为纯数字 - 缺失字段的处理规则 *** ### images(可选) - 类型:`string[]` - 每一项必须是 Data URI,例如: ```text data:image/png;base64,iVBORw0KGgoAAAANS... ``` - 并非所有 Provider / Model 都支持图片输入 - 图片数量过多可能导致请求失败 *** ### schema - 类型:`JSONSchemaArray | JSONSchemaObject` - 必填 - 定义模型**唯一允许返回的 JSON 结构** - 每一个字段都应提供清晰的 `description`,这是保证结果稳定的关键 *** ### options.provider - 类型:`Provider` - 可选,未指定时使用 Assistant 当前默认 Provider - 支持: - `"openai"` - `"gemini"` - `"anthropic"` - `"deepseek"` - `"openrouter"` - `{ custom: string }` *** ### options.modelId(可选) - 类型:`string` - 指定具体模型 ID - 必须与 Provider 实际支持的模型匹配 - 未指定时使用 Provider 默认模型 *** ## 返回值 ```ts Promise ``` - `R` 为调用方声明的泛型类型 - 返回结果应严格符合 Schema 描述 - 若模型无法生成合法结构,Promise 将被 reject *** ## 使用示例 ### 示例一:解析票据 / 收据,提取消费项目、时间和金额 该示例演示如何将一段票据文本解析为结构化数据,包括: - 整体消费时间(`purchasedAt`) - 币种(`currency`) - 消费项目列表(`items`) - 项目名称 - 项目时间(若无则为空) - 金额 - 合计金额(`total`) ```ts type ReceiptItem = { name: string time: string amount: number } type ReceiptParsed = { purchasedAt: string currency: string items: ReceiptItem[] total: number } const receiptText = ` Star Coffee 2026-01-08 14:23 Latte (Large) $5.50 Blueberry Muffin $3.20 Tax $0.79 Total $9.49 ` const parsed = await Assistant.requestStructuredData( [ "请分析以下票据文本,并提取结构化信息:", "- purchasedAt:整体消费时间,使用 ISO-8601 格式,若无法判断则返回空字符串", "- currency:币种代码(如 USD / EUR / CNY),若无法判断则返回空字符串", "- items:仅包含实际消费项目,不包含税费、合计等行", " - name:项目名称", " - time:项目级时间,若无则返回空字符串", " - amount:数值类型的金额", "- total:合计金额,若无则返回 -1", "", "票据内容:", receiptText ].join("\n"), { type: "object", description: "票据解析结果", properties: { purchasedAt: { type: "string", description: "整体消费时间(ISO-8601),若无则为空字符串" }, currency: { type: "string", description: "币种代码,若无法判断则为空字符串" }, items: { type: "array", description: "消费项目列表(不包含税费、合计等)", items: { type: "object", description: "单个消费项目", properties: { name: { type: "string", description: "项目名称" }, time: { type: "string", description: "项目时间(ISO-8601),若无则为空字符串" }, amount: { type: "number", description: "项目金额" } } } }, total: { type: "number", description: "合计金额,若不存在则为 -1" } } }, { provider: "openai" } ) // 建议在业务层将空字符串 / -1 归一化为 null console.log(parsed) ``` *** ### 示例二:生成数组结构 ```ts type Expense = { name: string amount: number } const expenses = await Assistant.requestStructuredData( "列出三项常见的日常支出及其大致金额", { type: "array", description: "支出列表", items: { type: "object", description: "单项支出", properties: { name: { type: "string", description: "支出名称" }, amount: { type: "number", description: "金额" } } } }, { provider: "gemini" } ) ``` *** ### 示例三:结合图片生成结构化结果 ```ts type ImageSummary = { description: string containsText: boolean } const summary = await Assistant.requestStructuredData( "分析这张图片的主要内容", ["data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD..."], { type: "object", description: "图片分析结果", properties: { description: { type: "string", description: "图片内容描述" }, containsText: { type: "boolean", description: "是否包含可识别文本" } } }, { provider: "openai" } ) ``` *** ## 使用建议与注意事项 - 当返回结果用于业务逻辑时,优先使用 `requestStructuredData` - Schema 描述越明确,结果越稳定 - 复杂业务规则不要放在 Schema 中,应由业务代码处理 ### 精确选择账号 在 options 中传入 `providerID`,可按稳定 ID 选择一个已配置账号;可以不传 `provider`,同时传入时必须匹配。未知或已删除的 ID 会报错,不会换号。通过 `await Assistant.getProviders()` 获取 ID 和模型信息,或在 Provider 面板复制 ID。仅传旧内置 `provider` 类型时,会选择该类型持久列表中的首个已配置账号。发现与模型选择器示例见 Assistant 总览。 --- url: /zh/guide/Camera Control/Camera Control Overview/index.md --- # 相机控制 通过 iPhone 相机控制键打开 Scripting 相机体验。系统直接打开主 App 时,会运行所选脚本的 `index.tsx`,注入 `Script.env === "camera_control"`,由脚本绘制完整 UI。此环境与 `index`、`home_screen` 的 API 范围一致,仍分别遵守系统版本、硬件、前台状态和脚本/系统权限要求。 相机控制入口应进入真实拍摄体验:拍摄时显示可见取景,并在页面上注册可用的 `onCameraCaptureEvent`。处理后续 `Script.onResume` 事件,返回拍摄体验时恢复界面;相机参数为 null 只表示没有新资源批次。避免停留在相机已停止的空页面,也不要重复处理旧批次。完整示例通过 **Close** 结束拍摄并释放资源。仅接收文件不会自动启动相机;用户点 **Start Camera** 或再次从相机入口进入时才恢复拍摄。 ## 系统拍摄入口要求 \*\*系统打开主 App 时:\*\*相机控制键和系统中的 **Scripting 相机** 控件都是拍摄入口。自定义脚本需要自行启动真实相机会话、显示预览并处理拍摄事件,脚本约 3 秒后仍未启动相机并提供可用拍摄交互时,Scripting 会尝试打开内置相机;脚本已打开系统相机页面时则继续使用该页面。这项保护只覆盖启动阶段,相机就绪后不会持续监控。之后停止相机却仍停留在拍摄入口,仍可能导致整个 App 被系统终止;JS 错误处理不能捕获系统对进程的终止。Apple 将该 intent 定义为拍摄体验入口,也有开发者在旧版 iOS 上[记录过主 App 被终止](https://developer.apple.com/forums/thread/769024)的情况。 保持活动取景不代表必须持续录像或保存照片、视频。 内置相机先保存拍摄完成的照片/视频,再通过 `Script.cameraControlParameter` 或 `Script.onResume` 交给原脚本。原脚本无法接收,或默认选择已变化时,批次会保留在“更多 → 默认脚本 → 相机控制 → 拍摄文件”,供手动处理。接管前会等待脚本释放相机。共享会话无法安全停止、权限拒绝或主线程无法响应时,兜底也可能无法完成;约 3 秒的等待不是系统保证。 系统入口未选择默认相机脚本时,先显示内置相机,再在其上打开脚本选择页。选择后会提示下次打开 Scripting 相机时生效;取消选择则仍留在相机。本次拍摄文件会保留供手动处理,不会自动交给刚选择的脚本。 \*\*系统打开锁屏拍摄扩展时:\*\*Apple 明确要求活动相机视图、硬件拍摄交互以及相机访问请求,否则扩展可能在启动后不久被终止。该原生相机由 Scripting 提供,详见 [Apple 拍摄扩展指南](https://developer.apple.com/documentation/lockedcameracapture/creating-a-camera-experience-for-the-lock-screen)。 \*\*停止与清理:\*\*上述文档没有定义主 App 的持续检查时序,也没有说明每次停止相机都会终止 App。不要依赖固定宽限时间或短暂开关相机的变通办法。退出时仍应 stop/dispose 资源;完成清理不代表已保证解除系统的拍摄入口检查。 仅接收已完成的文件不要求另开相机;若同一脚本也被选为系统相机目标,还应处理系统直接打开主 App 进行拍摄的情况。`Script.env === "camera_control"` 和相机参数为 null 都不能证明具体启动来源。App 内的“打开相机脚本”只测试脚本,不验证系统拍摄入口的行为。与拍摄无关的通用脚本应使用普通 App、Home 或快捷指令入口。参见 [Apple 启动指引](https://developer.apple.com/videos/play/wwdc2024/10204/?time=882)。 ## 设置 1. 从内置示例安装 **相机控制示例(Camera Control DEMO)**。 2. 打开 **更多 → 默认脚本 → 相机控制**,选择脚本。点“打开相机脚本”即可在没有相机键的设备上体验脚本页面。 3. 在支持的 iPhone 上,通过 **设置 → 相机 → 相机控制** 选择 Scripting。该系统选项由用户设置。 4. 也可将 **Scripting 相机** 控件添加到控制中心或锁定屏幕。 在 iOS 26+ 上打开 Scripting 相机时,会优先使用已有的主 App 窗口。相机提示和脚本选择显示在本次拍摄所在窗口,关闭内置相机后返回该窗口。 从锁屏入口进入时,Scripting 提供原生拍照、录像界面。拍摄保存完成后点“让 Scripting 处理”,系统按需认证,打开主 App 并把文件交给所选脚本。实际打开主 App 还是扩展由系统决定;即使已通过认证但仍停留在锁屏界面,也可能进入扩展。 扩展不执行用户脚本。脚本收到的是完成的文件,不是扩展进程中的实时相机会话。普通运行或无拍摄资源的主 App 相机入口中,`Script.cameraControlParameter === null`;扩展资源交付或内置兜底相机完成拍摄后则为非空对象。完整约定见[拍摄资源]()。 锁屏取景会在拍摄页面出现时准备;启动中会显示提示。相机不可用或被中断时会显示原因,可在恢复可用后继续,或点“重试相机”。录像必须先停止并保存完成,才能交给脚本。取消解锁或打开 App 失败时,已完成的文件仍保留;返回拍摄页面后可继续拍摄或再次点“让 Scripting 处理”。 首次锁屏交接前请先选择默认脚本。在相机控制示例中,点击 Captured files 下的照片或视频即可预览。如果先拍摄、后选择脚本,可到“更多 → 默认脚本 → 相机控制 → 拍摄文件”对已保存批次点“让 Scripting 处理”;仅选择脚本不会自动运行旧批次。 在锁屏录像模式中,点击模式选择旁的麦克风按钮切换是否录制声音;麦克风带斜线时录制无声视频。 ## 自定义脚本相机 在主 App 中使用 `AVCaptureSession`、`AVCaptureDeviceInput`、`AVCapturePhotoOutput`、`AVCaptureMovieFileOutput` 与 `CaptureVideoPreviewView`。给相机页面添加 `onCameraCaptureEvent` 处理实体快门事件,同时保留调用相同动作的触控按钮。系统缩放等控件仍使用 `supportsControls`、`canAddControl`、`setControlsDelegate`。secondary 不代表半按;不要在同一页面再附加一个 `AVCaptureEventInteraction`。 同级 `index.tsx` 示例可以预览扩展交付的照片/视频,由用户选择保存到照片库,并在没有资源时提供简单的脚本拍照界面。只有启动相机才请求相机权限;查看已有资源不会启动相机。系统拍摄入口与新增修饰符需要 iOS 18+。Simulator 可体验页面与数据流,但无法复现实体相机键事件。 请使用最新的 **相机控制示例(Camera Control DEMO 1.0.2)**。示例的 **Close** 会先等待相机停止,再关闭页面;已安装旧版示例时,请参考此完整示例更新其 `index.tsx`。 页面关闭时停止并 dispose 相机会话和播放器。等待权限时停止会取消该次启动,不会在脚本退出后迟到启动。保存到照片库沿用 Photos 权限;示例不会自动上传或自动保存到照片库。 请在脚本中处理相机生命周期错误。权限被拒绝、配置事务未结束、启动失败或本次启动已取消时,`startRunning()` 会拒绝。请使用同步的 `configure(() => { ... })`,或者在启动前为每个 `beginConfiguration()` 配对调用 `commitConfiguration()`。停止自建会话会结束其未完成的配置,并取消尚未完成的启动;之后可显式再次启动重试。`dispose()` 是最终释放,再次拍摄需要新建会话。 执行相机脚本或同步恢复回调时报告未捕获错误,该脚本会结束并释放拍摄资源,不再继续调用该失败脚本后续的恢复回调。请用 `try/catch` 或 `.catch()` 处理异步任务的错误;恢复流程不会等待恢复回调返回的 Promise。脚本退出后不再交付拍摄控件和拍摄交互回调;脚本仍在运行时,已分离的交互可以重新挂载。仅接收文件的入口或文件恢复回调可以处理批次后正常调用 `Script.exit()`,这会完成交付,不需要保持取景;未捕获错误仍算交付失败。这些保护不能替代前述系统拍摄入口要求。 ## 完整 index.tsx 示例 点击文档的示例入口即可运行,完整代码见同级 [index.tsx]()。 --- url: /zh/guide/Camera Control/Camera Control Overview/index_example.md --- # 示例 ```tsx import { Button, CaptureVideoPreviewView, Image, List, Navigation, NavigationStack, Path, Script, Section, Text, VStack, VideoPlayer, useEffect, useRef, useState, } from "scripting" import type { CameraControlAsset, CameraControlParameter } from "scripting" let alive = true let closing = false let incoming: CameraControlParameter | null = Script.cameraControlParameter // A null resume restores the capture experience without replaying a file batch. let captureRequested = !incoming && Script.env === "camera_control" let receive: (batch: CameraControlParameter | null) => void = batch => { if (batch) incoming = batch else captureRequested = Script.env === "camera_control" } const unsubscribe = Script.onResume(event => { if (!closing && (event.cameraControlParameter || Script.env === "camera_control")) receive(event.cameraControlParameter) }) let ownedSession: AVCaptureSession | null = null let ownedPlayer: AVPlayer | null = null let stopping: Promise = Promise.resolve() async function stopCamera() { const session = ownedSession ownedSession = null const previous = stopping const current = session ? session.stopRunning().finally(() => session.dispose()) : Promise.resolve() // A resource handoff can cancel a start while its permission request is open. // A later start must also await that earlier stop before acquiring the camera. stopping = Promise.all([previous, current]).then(() => {}, () => {}) await Promise.all([previous, current]) } function Demo() { const dismiss = Navigation.useDismiss() const [batch, setBatch] = useState(incoming) const [message, setMessage] = useState("Ready") const [image, setImage] = useState(null) const [video, setVideo] = useState(null) const [selected, setSelected] = useState(null) const [camera, setCamera] = useState<{ session: AVCaptureSession; device: AVCaptureDevice; photo: AVCapturePhotoOutput } | null>(null) const [busy, setBusy] = useState(false) const [captureMode, setCaptureMode] = useState(captureRequested) const pendingCamera = useRef(false) const revision = useRef(0) const working = useRef(false) const currentCamera = useRef(camera) currentCamera.current = camera const report = (value: string) => { if (alive) setMessage(value) } async function run(action: () => Promise) { if (!alive || closing || working.current) return const startedAt = revision.current working.current = true; setBusy(true) try { await action() } catch (error) { if (revision.current === startedAt) report(String(error)) } finally { working.current = false if (alive) { setBusy(false) // Do not lose an entry request that arrived while another action awaited. if (pendingCamera.current) void run(startCamera) } } } async function closeCamera() { if (closing) return closing = true // Reject new native file deliveries while this instance is closing. unsubscribe() revision.current += 1 pendingCamera.current = false setBusy(true) report("Closing camera…") // Keep the preview mounted until native stop finishes. Dismissing first // can make preview teardown wait synchronously for the running camera. try { await stopCamera() } catch (error) { report(String(error)) } finally { dismiss() } } async function startCamera() { pendingCamera.current = false const startedAt = revision.current const existing = currentCamera.current if (existing && ownedSession === existing.session && existing.session.isRunning) return currentCamera.current = null; setCamera(null) await stopCamera() if (!alive || closing || revision.current !== startedAt) return if (ownedPlayer) { ownedPlayer.dispose(); ownedPlayer = null; setVideo(null) } const device = AVCaptureDevice.default("video") if (!device) throw new Error("No camera is available. Simulator can still test the page and file handoff.") const session = new AVCaptureSession() const photo = new AVCapturePhotoOutput() ownedSession = session try { const input = new AVCaptureDeviceInput(device) session.configure(() => { if (!session.canAddInput(input)) throw new Error("Cannot add the camera input") session.addInput(input) if (!session.canAddOutput(photo)) throw new Error("Cannot add photo output") session.addOutput(photo) if (session.supportsControls) { const zoom = new AVCaptureSystemZoomSlider(device) if (session.canAddControl(zoom)) session.addControl(zoom) session.setControlsDelegate({ didBecomeActive() {}, willEnterFullscreenAppearance() {}, willExitFullscreenAppearance() {}, didBecomeInactive() {} }) } }) await session.startRunning() if (!alive || closing || revision.current !== startedAt || ownedSession !== session) { session.dispose(); if (ownedSession === session) ownedSession = null return } currentCamera.current = { session, device, photo } setCamera(currentCamera.current); setImage(null); setSelected(null) report("Camera ready. Touch Capture or use a physical capture button.") } catch (error) { session.dispose(); if (ownedSession === session) ownedSession = null; throw error } } async function capture() { const startedAt = revision.current const current = currentCamera.current if (!current || ownedSession !== current.session) return const folder = Path.join(FileManager.documentsDirectory, "Camera Control Demo") await FileManager.createDirectory(folder, true) const filePath = Path.join(folder, `photo-${Date.now()}.jpg`) const result = await current.photo.capturePhoto({ codec: "jpeg", photoFile: filePath }) if (!alive || closing || revision.current !== startedAt) return setImage(result.image) setSelected({ id: filePath, type: "photo", filePath, typeIdentifier: "public.jpeg", capturedAt: Date.now() }) report(`Photo saved: ${filePath}`) } async function preview(asset: CameraControlAsset) { const startedAt = revision.current // Keep the visible viewfinder alive in a Camera Control capture experience. if (!captureRequested) { await stopCamera(); currentCamera.current = null; if (alive) setCamera(null) } if (!alive || closing || revision.current !== startedAt) return setSelected(asset); setImage(null) ownedPlayer?.dispose(); ownedPlayer = null; setVideo(null) if (asset.type === "photo") { const decoded = UIImage.fromFile(asset.filePath) if (!decoded) throw new Error("Could not decode the photo") setImage(decoded) } else { const player = new AVPlayer() if (!player.setSource(asset.filePath)) { player.dispose(); throw new Error("Could not open the video") } ownedPlayer = player; setVideo(player) } report(`${asset.type}: ${asset.filePath}`) } useEffect(() => { receive = next => { if (!alive || closing) return if (!next) { captureRequested = true; setCaptureMode(true) pendingCamera.current = true if (!working.current) void run(startCamera) return } incoming = next revision.current += 1 setBatch(next); setSelected(null); setImage(null) ownedPlayer?.dispose(); ownedPlayer = null; setVideo(null) report(`Received ${next.assets.length} files · ${next.captureId}`) if (captureRequested && currentCamera.current?.session === ownedSession && ownedSession?.isRunning) { // A batch update must not tear down a live, visible capture experience. return } currentCamera.current = null; setCamera(null) void stopCamera().catch(error => report(String(error))) if (captureRequested) { pendingCamera.current = true if (!working.current) void run(startCamera) } } // File handoff alone never starts capture or repeats file processing. if (captureRequested) void run(startCamera) return () => { receive = () => {}; currentCamera.current = null } }, []) return { if (event.phase === "ended") void run(capture) }, }}> {camera ? : null} { void closeCamera() }} disabled={closing} /> }}>
Entry}> {`Environment: ${Script.env}`} {message} {batch ? `Capture batch: ${batch.captureId}` : "No handed-off batch"}
{batch ?
Captured files}> {batch.assets.map(asset =>
: null}
Script camera}>
{image ? : null} {video ? : null} {selected ? )} ``` 这些 action 会调用当前闹钟对应的原生 `AlarmManager` 操作: - `pause` - `resume` - `stop` - 当 alert 的 secondary button 使用 `secondaryButtonBehavior: "countdown"` 时,提供 `secondary` 如果需要额外的脚本业务逻辑,可以另外注册自己的 `AppIntent` 并用于普通 Live Activity 按钮。控制闹钟自身状态时,推荐优先使用 `state.actions.*.intent`。 *** ## 注意事项 - `AlarmManager` 的 alert `stopIntent` 和 `secondaryIntent` 仍然属于系统 alert 展示。 - 自定义 Live Activity UI 中的暂停、继续、停止和倒计时按钮应该使用 `state.actions.*.intent`。 - 灵动岛 compact 区域要尽量小,优先使用 SF Symbols、短文案和系统字体。 - iOS 26 上,锁屏和展开灵动岛中的可见控件建议使用 `buttonStyle="glass"` 或 `buttonStyle="glassProminent"`。 --- url: /zh/guide/Changelog/3.0.0/Alarm/AlarmManager.md --- # AlarmManager (闹钟) `AlarmManager` (iOS 26+) 是 Scripting 提供的全局 API,用于创建和管理基于 AlarmKit 的闹钟、定时器和倒计时提醒。它不需要导入,可直接在脚本中使用。 这个 API 适合以下场景: - 创建一次性闹钟,例如“今晚 22:30 提醒我” - 创建每天或每周重复的闹钟 - 创建番茄钟、运动计时器、倒计时等短时提醒 - 自定义提醒界面的标题、按钮、颜色、图标和元数据 - 结合 `AppIntent` 让提醒界面的按钮触发脚本逻辑 - 监听闹钟状态变化并同步更新 UI *** ## 使用前提 建议在使用前先判断当前环境是否支持 AlarmKit: ```tsx if (!AlarmManager.isAvailable) { console.log("当前系统不支持 AlarmKit") } ``` 如果当前设备或系统版本不支持,相关方法可能无法正常工作。 *** ## 基本概念 `AlarmManager` 主要围绕以下对象工作: - `Alarm`:已存在的闹钟实例 - `Schedule`:触发时间规则 - `Countdown`:倒计时参数 - `Button`:提醒界面按钮样式 - `Sound`:提醒声音 - `AlertPresentation`:提醒触发时的展示内容 - `CountdownPresentation`:倒计时进行中的展示内容 - `PausedPresentation`:倒计时暂停时的展示内容 - `Attributes`:提醒界面的整体展示属性 - `Configuration`:最终用于创建闹钟、定时器、倒计时的配置对象 *** ## Alarm ID 规则 创建闹钟时传入的 `id` 必须使用: ```tsx UUID.string() ``` 生成。 不要手动拼接固定字符串,也不要复用旧 ID。每次创建新的闹钟、定时器或倒计时时,都应生成一个新的 UUID 字符串。 正确示例: ```tsx const id = UUID.string() ``` 不推荐: ```tsx const id = "morning-alarm" const id = `timer-${Date.now()}` ``` 后续对闹钟的 `cancel`、`stop`、`pause`、`resume`、`startCountdown` 等操作,都需要使用创建时对应的同一个 ID。 *** ## AlarmState ```tsx type AlarmState = "scheduled" | "countdown" | "paused" | "alerting" ``` 表示闹钟当前状态。 ### `"scheduled"` 表示闹钟已创建,处于等待触发状态。 常见于: - 固定时间闹钟 - 每周重复闹钟 - 尚未开始的倒计时流程 ### `"countdown"` 表示当前处于倒计时进行中。 常见于: - 已开始运行的定时器 - 已启动的倒计时提醒 ### `"paused"` 表示当前倒计时已暂停。 ### `"alerting"` 表示提醒已经触发,当前处于提醒展示或响铃状态。 *** ## SecondaryButtonBehavior ```tsx type SecondaryButtonBehavior = "countdown" | "custom" ``` 控制提醒界面第二按钮的行为方式。 ### `"countdown"` 第二按钮用于启动一个倒计时行为。 通常适合“稍后提醒我”“再过几分钟提醒一次”这类场景。 ### `"custom"` 第二按钮作为自定义按钮存在,实际行为由 `secondaryIntent` 决定。 *** ## AlarmAppIntent ```tsx type AlarmAppIntent = AppIntent ``` 表示可绑定到闹钟按钮上的 `AppIntent`。 它主要用于: - 停止按钮触发额外业务逻辑 - 次要按钮触发自定义动作 - 与 Live Activity、Widget、ControlWidget 等机制联动 可配置的位置包括: - `Configuration.alarm(...).stopIntent` - `Configuration.alarm(...).secondaryIntent` - `Configuration.timer(...).stopIntent` - `Configuration.timer(...).secondaryIntent` - `Configuration.countdown(...).stopIntent` - `Configuration.countdown(...).secondaryIntent` 注意这里要求的 `AppIntent` 协议类型是: ```tsx AppIntentProtocol.LiveActivityIntent ``` 也就是说,给 `AlarmManager` 绑定的意图应当使用 `LiveActivityIntent` 协议注册。 后文有完整示例。 *** ## AlarmUpdateListener ```tsx type AlarmUpdateListener = (alarms: Alarm[]) => void ``` 用于监听闹钟列表变化的回调函数。 当闹钟被创建、取消、暂停、恢复、开始倒计时或状态发生变化时,监听器会收到最新的 `Alarm[]`。 *** ## Alarm ```tsx class Alarm { readonly id: string readonly state: AlarmState readonly schedule?: Schedule | null readonly countdownDuration?: Countdown | null } ``` 表示一个已存在的闹钟对象。 ### `id` ```tsx readonly id: string ``` 闹钟唯一标识符。 创建闹钟时必须使用 `UUID.string()` 生成,后续取消、停止、暂停、恢复等操作都依赖这个值。 ### `state` ```tsx readonly state: AlarmState ``` 当前闹钟的状态。 ### `schedule` ```tsx readonly schedule?: Schedule | null ``` 闹钟的时间规则。 纯定时器场景下不一定有 `schedule`。 ### `countdownDuration` ```tsx readonly countdownDuration?: Countdown | null ``` 倒计时相关配置。 *** ## Schedule ```tsx class Schedule { readonly type: "fixed" | "relative" readonly date?: Date | null readonly hour?: number | null readonly minute?: number | null readonly weekdays?: number[] | null static fixed(date: Date): Schedule static relative(hour: number, minute: number): Schedule static weekly(hour: number, minute: number, weekdays: number[]): Schedule } ``` 用于描述闹钟的触发时间规则。 ### `type` ```tsx readonly type: "fixed" | "relative" ``` 表示时间规则类型。 - `"fixed"`:固定绝对时间 - `"relative"`:按小时和分钟规则安排 ### `date` ```tsx readonly date?: Date | null ``` 固定时间闹钟的具体触发时间。 ### `hour` ```tsx readonly hour?: number | null ``` 触发小时。 ### `minute` ```tsx readonly minute?: number | null ``` 触发分钟。 ### `weekdays` ```tsx readonly weekdays?: number[] | null ``` 每周重复触发的星期数组。 具体 weekday 的编号语义以你的底层实现为准。通常会使用 1 到 7 表示一周中的某几天。 ### `Schedule.fixed(date)` ```tsx static fixed(date: Date): Schedule ``` 创建一个固定时间触发的日程。 ```tsx const schedule = AlarmManager.Schedule.fixed( new Date("2026-03-20T22:30:00") ) ``` ### `Schedule.relative(hour, minute)` ```tsx static relative(hour: number, minute: number): Schedule ``` 创建一个按时分安排的规则。 通常适合“每天某个时间”的提醒。 ```tsx const schedule = AlarmManager.Schedule.relative(7, 30) ``` ### `Schedule.weekly(hour, minute, weekdays)` ```tsx static weekly(hour: number, minute: number, weekdays: number[]): Schedule ``` 创建一个每周重复的提醒规则。 ```tsx const schedule = AlarmManager.Schedule.weekly(8, 0, [2, 3, 4, 5, 6]) ``` *** ## Countdown ```tsx class Countdown { readonly preAlert?: number | null readonly postAlert?: number | null static create(options?: { preAlert?: DurationInSeconds | null postAlert?: DurationInSeconds | null }): Countdown } ``` 用于定义倒计时相关参数。 ### `preAlert` ```tsx readonly preAlert?: number | null ``` 提醒前的倒计时时长,单位为秒。 ### `postAlert` ```tsx readonly postAlert?: number | null ``` 提醒后的附加时长,单位为秒。 具体行为取决于底层实现。 ### `Countdown.create(options?)` ```tsx static create(options?: { preAlert?: DurationInSeconds | null postAlert?: DurationInSeconds | null }): Countdown ``` 创建倒计时配置对象。 ```tsx const countdown = AlarmManager.Countdown.create({ preAlert: 10 * 60, postAlert: 5 * 60 }) ``` *** ## Button ```tsx class Button { static create(options: { title?: string textColor?: Color systemImageName?: string }): Button } ``` 用于定义提醒界面按钮样式。 ### 参数 #### `title` 按钮标题。 #### `textColor` 按钮文字颜色。 文档中的 `Color` 建议使用十六进制字符串形式,例如: ```tsx "#ffffff" "#ff9500" "#34c759" ``` #### `systemImageName` SF Symbols 图标名称。 ### `Button.create(options)` ```tsx static create(options: { title?: string textColor?: Color systemImageName?: string }): Button ``` ```tsx const stopButton = AlarmManager.Button.create({ title: "停止", textColor: "#ffffff", systemImageName: "stop.fill" }) const snoozeButton = AlarmManager.Button.create({ title: "稍后", textColor: "#ffffff", systemImageName: "timer" }) ``` *** ## Sound ```tsx class Sound { static default(): Sound static named(name: string): Sound } ``` 用于定义提醒声音。 ### `Sound.default()` ```tsx static default(): Sound ``` 使用系统默认声音。 ```tsx const sound = AlarmManager.Sound.default() ``` ### `Sound.named(name)` ```tsx static named(name: string): Sound ``` 使用指定名称的声音。 ```tsx const sound = AlarmManager.Sound.named("bell") ``` 可用名称取决于你的底层实现与系统支持情况。 *** ## AlertPresentation ```tsx class AlertPresentation { static create(options: { title: string stopButton?: Button | null secondaryButton?: Button | null secondaryBehavior?: SecondaryButtonBehavior | null }): AlertPresentation } ``` 用于定义提醒触发时的展示内容。 ### 参数 #### `title` 提醒标题,必填。 #### `stopButton` > **已废弃。** 从 iOS 26.1 起,提醒响起时的停止按钮由系统以 slider 形式渲染,不再使用自定义按钮。`stopButton` 仅为向后兼容保留,在 iOS 26.1+ 会被忽略,可以不填。 停止按钮样式(仅 iOS 26.0 回退使用)。 #### `secondaryButton` 第二按钮样式。 #### `secondaryBehavior` 第二按钮行为,可选值: - `"countdown"` - `"custom"` ### `AlertPresentation.create(options)` ```tsx static create(options: { title: string stopButton?: Button | null secondaryButton?: Button | null secondaryBehavior?: SecondaryButtonBehavior | null }): AlertPresentation ``` ```tsx const alert = AlarmManager.AlertPresentation.create({ title: "起床时间到了", stopButton: AlarmManager.Button.create({ title: "关闭", textColor: "#ffffff", systemImageName: "xmark" }), secondaryButton: AlarmManager.Button.create({ title: "稍后提醒", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "countdown" }) ``` *** ## CountdownPresentation ```tsx class CountdownPresentation { static create(title?: string | null, pauseButton?: Button | null): CountdownPresentation } ``` 用于定义倒计时进行中的展示内容。 ### `CountdownPresentation.create(title?, pauseButton?)` ```tsx static create(title?: string | null, pauseButton?: Button | null): CountdownPresentation ``` ```tsx const countdownPresentation = AlarmManager.CountdownPresentation.create( "专注计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ) ``` *** ## PausedPresentation ```tsx class PausedPresentation { static create(title?: string | null, resumeButton?: Button | null): PausedPresentation | null } ``` 用于定义倒计时暂停时的展示内容。 ### `PausedPresentation.create(title?, resumeButton?)` ```tsx static create(title?: string | null, resumeButton?: Button | null): PausedPresentation | null ``` ```tsx const pausedPresentation = AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ) ``` *** ## Attributes ```tsx class Attributes { static create(options: { alert: AlertPresentation countdown?: CountdownPresentation | null paused?: PausedPresentation | null tintColor?: Color metadata?: Record liveActivity?: { name: string } }): Attributes | null } ``` 用于组合提醒界面的完整展示属性。 ### 参数 #### `alert` 提醒触发时的展示内容,必填。 #### `countdown` 倒计时状态的展示内容。 #### `paused` 暂停状态的展示内容。 #### `tintColor` 整体强调色,建议使用十六进制字符串: ```tsx "#ffffff" "#007aff" "#ff9500" ``` #### `metadata` 附加元数据,可用于记录业务信息。 #### `liveActivity` 可选的自定义 Live Activity UI 绑定。如果当前脚本提供了 `alarm_live_activity.tsx`,并用 `AlarmLiveActivity.register` 注册了同名 UI,Scripting 会在锁屏和灵动岛渲染该 UI;否则使用内置闹钟 UI。 ```tsx liveActivity: { name: "FocusTimerActivity" } ``` 完整 UI builder API 请参考 **Alarm Live Activity** 文档。 ### `Attributes.create(options)` ```tsx static create(options: { alert: AlertPresentation countdown?: CountdownPresentation | null paused?: PausedPresentation | null tintColor?: Color metadata?: Record liveActivity?: { name: string } }): Attributes | null ``` ```tsx const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "番茄钟结束", stopButton: AlarmManager.Button.create({ title: "完成", textColor: "#ffffff", systemImageName: "checkmark" }) }), countdown: AlarmManager.CountdownPresentation.create( "专注中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#ff9500", metadata: { type: "pomodoro", source: "study-script" }, liveActivity: { name: "FocusTimerActivity" } }) ``` *** ## Configuration ```tsx class Configuration { static alarm(options: { schedule?: Schedule | null attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null static timer(options: { duration: DurationInSeconds attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null static countdown(options: { countdown?: Countdown | null schedule?: Schedule | null attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null } ``` 用于生成最终可传给 `AlarmManager.schedule()` 的配置对象。 *** ## Configuration.alarm ```tsx static alarm(options: { schedule?: Schedule | null attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null ``` 创建普通闹钟配置。 适合: - 一次性固定时间提醒 - 每天提醒 - 每周重复提醒 ### 参数 #### `schedule` 触发时间规则。 #### `attributes` 提醒展示属性,必填。 #### `sound` 提醒声音。 #### `stopIntent` 停止按钮绑定的 `AppIntent`。 #### `secondaryIntent` 第二按钮绑定的 `AppIntent`。 ### 示例 ```tsx const schedule = AlarmManager.Schedule.fixed( new Date("2026-03-20T07:30:00") ) const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "早安,起床了", stopButton: AlarmManager.Button.create({ title: "关闭", textColor: "#ffffff", systemImageName: "xmark" }), secondaryButton: AlarmManager.Button.create({ title: "稍后", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "countdown" }), tintColor: "#34c759", metadata: { category: "morning" } }) const configuration = AlarmManager.Configuration.alarm({ schedule, attributes, sound: AlarmManager.Sound.default() }) ``` *** ## Configuration.timer ```tsx static timer(options: { duration: DurationInSeconds attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null ``` 创建定时器配置。 适合: - 番茄钟 - 运动计时器 - 烹饪提醒 - 短时专注任务 ### 参数 #### `duration` 定时器总时长,单位秒。 #### `attributes` 展示属性,必填。 #### `sound` 提醒声音。 #### `stopIntent` 停止动作绑定的 `AppIntent`。 #### `secondaryIntent` 第二按钮动作绑定的 `AppIntent`。 ### 示例 ```tsx const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "25分钟专注结束", stopButton: AlarmManager.Button.create({ title: "完成", textColor: "#ffffff", systemImageName: "checkmark" }) }), countdown: AlarmManager.CountdownPresentation.create( "专注中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "暂停中", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#ff9500", metadata: { mode: "focus" } }) const configuration = AlarmManager.Configuration.timer({ duration: 25 * 60, attributes, sound: AlarmManager.Sound.default() }) ``` *** ## Configuration.countdown ```tsx static countdown(options: { countdown?: Countdown | null schedule?: Schedule | null attributes: Attributes sound?: Sound | null stopIntent?: AlarmAppIntent | null secondaryIntent?: AlarmAppIntent | null }): Configuration | null ``` 创建倒计时提醒配置。 适合: - 到某个时间点后再进入倒计时 - 实现“稍后提醒我” - 自定义提醒前后的倒计时流程 ### 参数 #### `countdown` 倒计时参数。 #### `schedule` 触发日程。 #### `attributes` 展示属性,必填。 #### `sound` 提醒声音。 #### `stopIntent` 停止动作绑定的 `AppIntent`。 #### `secondaryIntent` 第二按钮动作绑定的 `AppIntent`。 ### 示例 ```tsx const countdown = AlarmManager.Countdown.create({ preAlert: 15 * 60, postAlert: 5 * 60 }) const schedule = AlarmManager.Schedule.relative(21, 0) const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "准备休息", stopButton: AlarmManager.Button.create({ title: "知道了", textColor: "#ffffff", systemImageName: "bed.double.fill" }), secondaryButton: AlarmManager.Button.create({ title: "15分钟后提醒", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "countdown" }), countdown: AlarmManager.CountdownPresentation.create( "休息倒计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "恢复", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#af52de", metadata: { scene: "night" } }) const configuration = AlarmManager.Configuration.countdown({ countdown, schedule, attributes, sound: AlarmManager.Sound.default() }) ``` *** ## isAvailable ```tsx const isAvailable: boolean ``` 表示当前环境是否支持 AlarmKit。 ```tsx if (!AlarmManager.isAvailable) { throw new Error("当前系统不支持 AlarmManager") } ``` *** ## alarms ```tsx function alarms(): Promise ``` 获取当前所有闹钟。 ### 返回值 返回 `Promise`。 ### 示例 ```tsx const list = await AlarmManager.alarms() for (const alarm of list) { console.log(alarm.id, alarm.state) } ``` *** ## schedule ```tsx function schedule(id: string, configuration: Configuration): Promise ``` 根据配置创建并调度一个闹钟。 ### 参数 #### `id` 闹钟唯一标识符。 必须使用 `UUID.string()` 生成。 #### `configuration` 通过 `AlarmManager.Configuration.alarm()`、`timer()` 或 `countdown()` 创建的配置对象。 ### 返回值 返回创建后的 `Alarm`。 ### 示例 ```tsx const configuration = AlarmManager.Configuration.timer({ duration: 10 * 60, attributes: AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "10分钟到了", stopButton: AlarmManager.Button.create({ title: "结束", textColor: "#ffffff", systemImageName: "stop.fill" }) }), countdown: AlarmManager.CountdownPresentation.create( "倒计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "暂停中", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#007aff" }), sound: AlarmManager.Sound.default() }) const id = UUID.string() const alarm = await AlarmManager.schedule(id, configuration) console.log(alarm.id, alarm.state) ``` *** ## cancel ```tsx function cancel(id: string): Promise ``` 取消指定闹钟。 ### 参数 #### `id` 要取消的闹钟 ID。 ### 返回值 返回是否取消成功。 ### 示例 ```tsx const success = await AlarmManager.cancel(alarmId) console.log("取消结果:", success) ``` *** ## stop ```tsx function stop(id: string): Promise ``` 停止指定闹钟或提醒。 通常用于提醒已经触发,或者需要主动终止当前流程时。 ### 示例 ```tsx const success = await AlarmManager.stop(alarmId) console.log("停止结果:", success) ``` *** ## pause ```tsx function pause(id: string): Promise ``` 暂停指定倒计时或定时器。 ### 示例 ```tsx const success = await AlarmManager.pause(alarmId) console.log("暂停结果:", success) ``` *** ## resume ```tsx function resume(id: string): Promise ``` 恢复已暂停的倒计时或定时器。 ### 示例 ```tsx const success = await AlarmManager.resume(alarmId) console.log("恢复结果:", success) ``` *** ## startCountdown ```tsx function startCountdown(id: string): Promise ``` 启动指定闹钟的倒计时流程。 通常适用于通过 `Configuration.countdown()` 创建的配置,或提醒流程中存在“稍后提醒”语义的场景。 ### 示例 ```tsx const success = await AlarmManager.startCountdown(alarmId) console.log("开始倒计时:", success) ``` *** ## addAlarmUpdateListener ```tsx function addAlarmUpdateListener(listener: AlarmUpdateListener): void ``` 添加闹钟更新监听器。 当闹钟列表发生变化时,回调会收到最新的 `Alarm[]`。 ### 示例 ```tsx const listener = (alarms: AlarmManager.Alarm[]) => { console.log("闹钟数量:", alarms.length) for (const alarm of alarms) { console.log(alarm.id, alarm.state) } } AlarmManager.addAlarmUpdateListener(listener) ``` *** ## removeAlarmUpdateListener ```tsx function removeAlarmUpdateListener(listener?: AlarmUpdateListener): void ``` 移除之前添加的监听器,不传移除所有。 ### 参数 #### `listener` 要移除的监听器函数。 如果省略该参数,其具体行为以你的底层实现为准。 ### 示例 ```tsx const listener = (alarms: AlarmManager.Alarm[]) => { console.log("更新:", alarms.length) } AlarmManager.addAlarmUpdateListener(listener) AlarmManager.removeAlarmUpdateListener(listener) ``` *** ## 在 AlarmManager 中使用 AppIntent `AlarmManager` 支持通过 `stopIntent` 和 `secondaryIntent` 把按钮行为交给 `AppIntent` 处理。 这使得提醒按钮不仅可以停止或触发倒计时,还可以进一步执行脚本逻辑,例如: - 停止提醒后写入本地状态 - 点击“完成”后更新任务状态 - 点击“稍后提醒”后刷新 Widget 或 Live Activity - 结合其他全局 API 执行业务逻辑 *** ## AppIntent 的定义位置 所有 `AppIntent` 都必须定义在: ```tsx app_intents.tsx ``` 中。 不要把它们定义在 `widget.tsx`、`live_activity.tsx`、`control_widget.tsx` 或普通脚本文件中。 并且在执行时: ```tsx Script.env === "app_intents" ``` 也就是说,`perform` 函数运行在 `app_intents` 环境。 *** ## AppIntent 相关类型 ### AppIntent 表示一个具体的意图实例。 | 字段名 | 类型 | 描述 | | ---------- | ------------------- | -------------------- | | `script` | `string` | 脚本路径,由系统内部生成 | | `name` | `string` | 意图名称,唯一标识该 AppIntent | | `protocol` | `AppIntentProtocol` | 意图协议类型 | | `params` | `T` | 执行时的参数 | ### AppIntentFactory ```tsx type AppIntentFactory = (params: T) => AppIntent ``` 用于根据参数创建 `AppIntent` 实例。 ### AppIntentPerform ```tsx type AppIntentPerform = (params: T) => Promise ``` 表示被触发后执行的异步逻辑。 ### AppIntentProtocol | 枚举成员 | 描述 | | ---------------------- | ------------------ | | `AppIntent` | 普通意图 | | `AudioPlaybackIntent` | 音频播放相关意图 | | `AudioRecordingIntent` | 音频录制相关意图 | | `LiveActivityIntent` | Live Activity 相关意图 | 对于 `AlarmManager`,需要使用: ```tsx AppIntentProtocol.LiveActivityIntent ``` *** ## AppIntentManager.register ```tsx static register(options: { name: string protocol: AppIntentProtocol perform: AppIntentPerform }): AppIntentFactory ``` 用于注册一个新的 `AppIntent`。 ### 参数 #### `name` 意图名称,必须唯一。 #### `protocol` 意图协议类型。 #### `perform` 当意图被触发时执行的异步函数。 ### 返回值 返回一个工厂函数,可通过传入参数创建对应的 `AppIntent` 实例。 *** ## AlarmManager 的 AppIntent 示例 下面示例展示如何在 `app_intents.tsx` 中定义两个可供 `AlarmManager` 使用的意图。 ```tsx /// app_intents.tsx export const StopFocusAlarmIntent = AppIntentManager.register({ name: "StopFocusAlarmIntent", protocol: AppIntentProtocol.LiveActivityIntent, perform: async ({ alarmId, taskId }: { alarmId: string; taskId: string }) => { console.log("停止提醒:", alarmId, taskId) // 这里可以执行你的业务逻辑 // 例如更新任务状态、记录日志、刷新界面等 await Storage.set(`task:${taskId}:finished`, true) Widget.reloadAll() } }) export const SnoozeFocusAlarmIntent = AppIntentManager.register({ name: "SnoozeFocusAlarmIntent", protocol: AppIntentProtocol.LiveActivityIntent, perform: async ({ alarmId }: { alarmId: string }) => { console.log("稍后提醒:", alarmId) // 可按需刷新 UI 或做其他状态处理 Widget.reloadAll() } }) ``` *** ## 把 AppIntent 绑定到 AlarmManager 定义好 `AppIntent` 后,可以通过 `stopIntent` 和 `secondaryIntent` 传入配置中。 ```tsx const alarmId = UUID.string() const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "专注时间结束", stopButton: AlarmManager.Button.create({ title: "完成", textColor: "#ffffff", systemImageName: "checkmark" }), secondaryButton: AlarmManager.Button.create({ title: "稍后5分钟", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "custom" }), countdown: AlarmManager.CountdownPresentation.create( "倒计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#007aff", metadata: { type: "focus" } }) const configuration = AlarmManager.Configuration.timer({ duration: 25 * 60, attributes, sound: AlarmManager.Sound.default(), stopIntent: StopFocusAlarmIntent({ alarmId, taskId: "task_001" }), secondaryIntent: SnoozeFocusAlarmIntent({ alarmId }) }) await AlarmManager.schedule(alarmId, configuration) ``` 上面这个例子里: - 停止按钮会触发 `StopFocusAlarmIntent` - 第二按钮会触发 `SnoozeFocusAlarmIntent` - 第二按钮行为设为了 `"custom"`,因此其实际逻辑由 `secondaryIntent` 决定 *** ## 使用 countdown 行为的第二按钮 如果你希望第二按钮直接走 AlarmKit 的倒计时语义,可使用: ```tsx secondaryBehavior: "countdown" ``` 示例: ```tsx const alarmId = UUID.string() const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "该休息了", stopButton: AlarmManager.Button.create({ title: "关闭", textColor: "#ffffff", systemImageName: "xmark" }), secondaryButton: AlarmManager.Button.create({ title: "10分钟后提醒", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "countdown" }), countdown: AlarmManager.CountdownPresentation.create( "稍后提醒倒计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#ff3b30" }) const configuration = AlarmManager.Configuration.countdown({ countdown: AlarmManager.Countdown.create({ preAlert: 10 * 60 }), attributes, sound: AlarmManager.Sound.default() }) await AlarmManager.schedule(alarmId, configuration) ``` 这种方式更适合“稍后提醒”这种标准倒计时交互。 *** ## 创建一次性闹钟 ```tsx if (!AlarmManager.isAvailable) { throw new Error("当前环境不支持 AlarmKit") } const alarmId = UUID.string() const schedule = AlarmManager.Schedule.fixed( new Date("2026-03-20T22:30:00") ) const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "该休息了", stopButton: AlarmManager.Button.create({ title: "关闭", textColor: "#ffffff", systemImageName: "xmark" }), secondaryButton: AlarmManager.Button.create({ title: "10分钟后提醒", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "countdown" }), countdown: AlarmManager.CountdownPresentation.create( "稍后提醒倒计时中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#ff3b30", metadata: { purpose: "sleep" } }) const configuration = AlarmManager.Configuration.alarm({ schedule, attributes, sound: AlarmManager.Sound.default() }) const alarm = await AlarmManager.schedule(alarmId, configuration) console.log("已创建:", alarm.id, alarm.state) ``` *** ## 创建每周重复闹钟 ```tsx const alarmId = UUID.string() const schedule = AlarmManager.Schedule.weekly(7, 30, [2, 3, 4, 5, 6]) const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "工作日早起提醒", stopButton: AlarmManager.Button.create({ title: "起床", textColor: "#ffffff", systemImageName: "sun.max.fill" }) }), tintColor: "#34c759", metadata: { tag: "weekday-morning" } }) const configuration = AlarmManager.Configuration.alarm({ schedule, attributes, sound: AlarmManager.Sound.default() }) await AlarmManager.schedule(alarmId, configuration) ``` *** ## 创建番茄钟定时器 ```tsx const alarmId = UUID.string() const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "当前专注时段已结束", stopButton: AlarmManager.Button.create({ title: "完成", textColor: "#ffffff", systemImageName: "checkmark.circle.fill" }) }), countdown: AlarmManager.CountdownPresentation.create( "专注中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "专注已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#ff9500", metadata: { type: "pomodoro", duration: "1500" } }) const configuration = AlarmManager.Configuration.timer({ duration: 25 * 60, attributes, sound: AlarmManager.Sound.default() }) await AlarmManager.schedule(alarmId, configuration) ``` *** ## 创建可手动启动的倒计时提醒 ```tsx const alarmId = UUID.string() const countdown = AlarmManager.Countdown.create({ preAlert: 5 * 60, postAlert: 60 }) const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "稍后提醒时间到了", stopButton: AlarmManager.Button.create({ title: "知道了", textColor: "#ffffff", systemImageName: "bell.slash.fill" }) }), countdown: AlarmManager.CountdownPresentation.create( "稍后提醒中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "倒计时已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#af52de" }) const configuration = AlarmManager.Configuration.countdown({ countdown, attributes, sound: AlarmManager.Sound.default() }) await AlarmManager.schedule(alarmId, configuration) await AlarmManager.startCountdown(alarmId) ``` *** ## 查询与控制闹钟 ```tsx const alarms = await AlarmManager.alarms() console.log("当前闹钟数量:", alarms.length) const firstAlarm = alarms[0] if (firstAlarm) { await AlarmManager.pause(firstAlarm.id) await AlarmManager.resume(firstAlarm.id) await AlarmManager.stop(firstAlarm.id) } ``` *** ## 监听闹钟状态变化 ```tsx const listener = (alarms: AlarmManager.Alarm[]) => { const summary = alarms.map(item => ({ id: item.id, state: item.state })) console.log("最新闹钟状态:", JSON.stringify(summary, null, 2)) } AlarmManager.addAlarmUpdateListener(listener) // 不再需要时移除 // AlarmManager.removeAlarmUpdateListener(listener) ``` *** ## 执行环境说明 `AlarmManager` 本身是全局 API,可以在普通脚本中直接使用。 但如果你给 `AlarmManager` 绑定了 `AppIntent`,那么这些意图的 `perform` 函数执行环境为: ```tsx Script.env === "app_intents" ``` 这意味着: - `AlarmManager.schedule()` 等闹钟创建逻辑,通常运行在普通脚本环境 - `stopIntent` / `secondaryIntent` 对应的逻辑,运行在 `app_intents.tsx` 中定义的 `perform` 里 - 你可以在 `perform` 中执行网络请求、状态更新、Widget 刷新、Live Activity 刷新等逻辑 *** ## 最佳实践 ### 始终使用 UUID.string() 生成 alarmId 这是 `AlarmManager` 的硬性要求。不要自己构造 ID。 ```tsx const alarmId = UUID.string() ``` ### 保留创建时的 alarmId 创建成功后,应自行保存该 `alarmId`,方便后续暂停、恢复、停止、取消。 ### 优先使用 metadata 保存业务信息 比如任务 ID、场景、来源等。 ```tsx metadata: { taskId: "task_123", scene: "study", source: "focus-page" } ``` ### 把 AppIntent 集中定义在 app\_intents.tsx 不要散落在不同文件中,方便维护。 ### 为 AppIntent 定义明确的参数类型 这样能获得更好的类型检查和自动补全。 ```tsx perform: async ({ alarmId, taskId }: { alarmId: string; taskId: string }) => { // ... } ``` ### 需要标准“稍后提醒”时优先使用 countdown 如果只是实现标准的“几分钟后再提醒”,推荐使用: ```tsx secondaryBehavior: "countdown" ``` 如果需要完全自定义逻辑,再使用: ```tsx secondaryBehavior: "custom" secondaryIntent: ... ``` *** ## 注意事项 ### Attributes.create(...) 可能返回 null ```tsx const attributes = AlarmManager.Attributes.create(...) ``` 返回类型是 `Attributes | null`,建议在严格场景下进行判空。 ### Configuration 创建方法也可能返回 null ```tsx const configuration = AlarmManager.Configuration.timer(...) ``` 返回类型同样允许为 `null`,建议在调用 `schedule()` 前先校验。 ### pause、resume、startCountdown 不适用于所有闹钟类型 这些方法更适合定时器或倒计时场景。对于普通固定时间闹钟,某些操作可能没有实际意义。 *** ## 完整示例 下面给出一个包含 `AppIntent` 的完整示例。 ```tsx /// app_intents.tsx export const StopPomodoroIntent = AppIntentManager.register({ name: "StopPomodoroIntent", protocol: AppIntentProtocol.LiveActivityIntent, perform: async ({ alarmId, sessionId }: { alarmId: string; sessionId: string }) => { console.log("番茄钟结束:", alarmId, sessionId) await Storage.set(`pomodoro:${sessionId}:done`, true) Widget.reloadAll() } }) export const ExtendPomodoroIntent = AppIntentManager.register({ name: "ExtendPomodoroIntent", protocol: AppIntentProtocol.LiveActivityIntent, perform: async ({ alarmId, extraMinutes }: { alarmId: string; extraMinutes: number }) => { console.log("延长番茄钟:", alarmId, extraMinutes) Widget.reloadAll() } }) ``` ```tsx /// 普通脚本文件 async function main() { if (!AlarmManager.isAvailable) { console.log("当前系统不支持 AlarmManager") return } const listener = (alarms: AlarmManager.Alarm[]) => { console.log( "闹钟更新:", alarms.map(item => `${item.id}:${item.state}`).join(", ") ) } AlarmManager.addAlarmUpdateListener(listener) const alarmId = UUID.string() const attributes = AlarmManager.Attributes.create({ alert: AlarmManager.AlertPresentation.create({ title: "专注时间结束", stopButton: AlarmManager.Button.create({ title: "完成", textColor: "#ffffff", systemImageName: "checkmark" }), secondaryButton: AlarmManager.Button.create({ title: "延长5分钟", textColor: "#ffffff", systemImageName: "timer" }), secondaryBehavior: "custom" }), countdown: AlarmManager.CountdownPresentation.create( "专注中", AlarmManager.Button.create({ title: "暂停", textColor: "#ffffff", systemImageName: "pause.fill" }) ), paused: AlarmManager.PausedPresentation.create( "已暂停", AlarmManager.Button.create({ title: "继续", textColor: "#ffffff", systemImageName: "play.fill" }) ), tintColor: "#007aff", metadata: { feature: "focus-mode" } }) if (!attributes) { throw new Error("创建 Attributes 失败") } const configuration = AlarmManager.Configuration.timer({ duration: 15 * 60, attributes, sound: AlarmManager.Sound.default(), stopIntent: StopPomodoroIntent({ alarmId, sessionId: "session_001" }), secondaryIntent: ExtendPomodoroIntent({ alarmId, extraMinutes: 5 }) }) if (!configuration) { throw new Error("创建 Configuration 失败") } const alarm = await AlarmManager.schedule(alarmId, configuration) console.log("已创建闹钟:", alarm.id, alarm.state) const current = await AlarmManager.alarms() console.log("当前闹钟:", current.map(item => item.id)) await AlarmManager.pause(alarmId) await AlarmManager.resume(alarmId) // 结束后可移除监听 // AlarmManager.removeAlarmUpdateListener(listener) } main().catch(error => { console.log(String(error)) }) ``` --- url: /zh/guide/Changelog/3.0.0/FileManager.md --- # 文件管理器 FileManager 模块提供对文件系统的统一访问接口,是脚本与本地文件及 iCloud 文件交互的主要方式。它支持对目录与文件进行读取、写入、拷贝、移动、删除、压缩、解压、符号链接操作,以及 iCloud 文件管理等功能。 *** ## 基本属性 ### `FileManager.scriptsDirectory: string` 存放脚本文件的目录路径。开发者编写的脚本会存储在该目录中。 ### `FileManager.isiCloudEnabled: boolean` 用于判断 iCloud 是否可用。若当前设备未登录 iCloud,或未授权 Scripting 使用 iCloud,该属性返回 `false`。 ### `FileManager.iCloudDocumentsDirectory: string` 返回 iCloud 的 `Documents` 目录路径。若 iCloud 未启用,调用该属性会抛出错误。使用前应检查 `FileManager.isiCloudEnabled`。 ### `FileManager.appGroupDocumentsDirectory: string` 返回 App Group 的共享 Documents 目录路径。存储于该目录的文件不会显示在系统的“文件”应用中,但 Widget 中运行的脚本可访问这些文件。 ### `FileManager.isWebDAVAvailable: boolean` 用于判断 WebDAV 是否已经完成配置并可用。 ### `FileManager.webDAVDocumentsDirectory: string` 返回 WebDAV 缓存下的 `Documents` 目录路径。写入到该目录的文件会在 WebDAV 配置可用后进入同步队列。 ### `FileManager.safariBrowserDirectory: string` 返回 Safari 浏览器用户脚本的数据根目录。这个目录会跟随 Settings 中的 Safari Browser Data 存储位置,里面包含 `userscripts/`、`storages/` 和 `downloads/`。 当普通 app 脚本需要查看或维护整套 Safari 扩展数据时,可以使用这个目录。 ### `FileManager.safariBrowserStorageDirectory: string` 返回 Safari 浏览器用户脚本的 GM value JSON 存储目录。它指向 `scripting-safari-extension/storages/`。 ### `FileManager.safariBrowserDownloadsDirectory: string` 返回 Safari 浏览器用户脚本通过 `GM.download` 保存文件的目录。它指向 `scripting-safari-extension/downloads/`。 ### `FileManager.safariBrowserUserscriptsDirectory: string` 返回从 Safari 扩展弹窗安装的用户脚本目录。它指向 `scripting-safari-extension/userscripts/`。 ### `FileManager.documentsDirectory: string` 返回本地的 `Documents` 目录路径。存储于该目录的文件可在“文件”应用中查看,但 Widget 不可访问。 ### `FileManager.temporaryDirectory: string` 返回临时目录路径,用于创建临时文件。系统可能在适当时机自动清除该目录内容。 *** ## iCloud 文件管理 ### `FileManager.isFileStoredIniCloud(filePath: string): boolean` 判断指定文件是否为存储于 iCloud 的文件。 | 参数 | 类型 | 说明 | | -------- | ------ | ---- | | filePath | string | 文件路径 | ### `FileManager.isiCloudFileDownloaded(filePath: string): boolean` 判断指定的 iCloud 文件是否已从云端下载到本地。 ### `FileManager.downloadFileFromiCloud(filePath: string): Promise` 下载指定的 iCloud 文件。 | 返回值 | 说明 | | ----------------- | ------ | | Promise\ | 下载是否成功 | 示例: ```ts if (FileManager.isiCloudEnabled) { const file = FileManager.iCloudDocumentsDirectory + "/data.json"; const ok = await FileManager.downloadFileFromiCloud(file); } ``` ### `FileManager.getShareUrlOfiCloudFile(path: string, expiration?: number): string` 生成 iCloud 文件的可分享下载链接。文件必须存在于 iCloud 且已上传。 | 参数 | 类型 | 说明 | | ---------- | --------- | --------------------------------------------------- | | path | string | 必须以 `FileManager.iCloudDocumentsDirectory` 为前缀的文件路径 | | expiration | number 可选 | 链接过期时间戳 | 使用时需配合 `try-catch` 捕获异常。 *** ## 目录与文件操作 支持异步(Promise)与同步(Sync)两种版本。同步方法会阻塞执行线程,在性能敏感场景应优先使用异步版本。 ### 创建目录 #### `createDirectory(path: string, recursive?: boolean): Promise` #### `createDirectorySync(path: string, recursive?: boolean): void` | 参数 | 类型 | 说明 | | --------- | ---------- | -------------------- | | path | string | 目录路径 | | recursive | boolean 可选 | 若为 true,则自动创建不存在的父目录 | ### 创建符号链接 #### `createLink(path: string, target: string): Promise` #### `createLinkSync(path: string, target: string): void` 在 `path` 创建指向 `target` 的符号链接。 ### 拷贝文件 #### `copyFile(path: string, newPath: string): Promise` #### `copyFileSync(path: string, newPath: string): void` ### 读取目录 #### `readDirectory(path: string, recursive?: boolean): Promise` #### `readDirectorySync(path: string, recursive?: boolean): string[]` 列出指定目录下所有内容,可递归。 ### 判断文件存在性 #### `exists(path: string): Promise` #### `existsSync(path: string): boolean` ### 文件书签管理 文件书签用于持久访问用户授权的外部文件。 | 方法 | 说明 | | ----------------------- | --------------------- | | `bookmarkExists(name)` | 判断书签是否存在 | | `getAllFileBookmarks()` | 获取所有书签名称与路径 | | `bookmarkedPath(name)` | 返回书签对应的路径,不存在时返回 null | 外部文件提供者离线、授权暂时不可用或启动恢复尚未完成时,`bookmarkedPath` 也返回 `null`;该调用不等待远程目录恢复。保存的书签不会因临时失败被删除,`bookmarkExists` 仍返回 `true`。`getAllFileBookmarks` 会保留这些名称,但不可用项的 `path` 是空字符串;使用路径前请检查非空。恢复网络后重新进入前台会后台重试,也可以在 Settings 的外部文件访问页面重新授权。 ### 判断文件类型 | 方法 | 返回 | 说明 | | --------------------------------- | ------- | -------- | | `isFile / isFileSync` | boolean | 是否为文件 | | `isDirectory / isDirectorySync` | boolean | 是否为目录 | | `isLink / isLinkSync` | boolean | 是否为符号链接 | | `isBinaryFile / isBinaryFileSync` | boolean | 是否为二进制文件 | *** ## 文件读写 支持三种读写格式:字符串、字节数组、Data。 ### 读取文件 | 方法 | 返回类型 | 说明 | | ------------------- | ---------- | ----------- | | readAsString / Sync | string | 指定编码读取文本内容 | | readAsBytes / Sync | Uint8Array | 读取为字节数组 | | readAsData / Sync | Data | 读取为 Data 对象 | ### 写入文件 | 方法 | 数据格式 | | -------------------- | ---------- | | writeAsString / Sync | string | | writeAsBytes / Sync | Uint8Array | | writeAsData / Sync | Data | 自动覆盖已有文件。 ### 追加内容 | 方法 | 数据格式 | | ----------------- | ------ | | appendText / Sync | string | | appendData / Sync | Data | 若文件或目录不存在将自动创建。 *** ## 文件信息与操作 ### `stat(path: string): Promise` ### `statSync(path: string): FileStat` 获取文件信息。若 path 为符号链接,会返回真实文件的状态。 ### `rename / renameSync` 移动或重命名文件或目录。 ### `remove / removeSync` 删除文件或目录(目录会递归删除)。 *** ## 压缩与解压 ### `zip(srcPath: string, destPath: string, shouldKeepParent?: boolean): Promise` ### `zipSync(srcPath: string, destPath: string, shouldKeepParent?: boolean): void` 压缩文件或目录为 zip。 ### `unzip(srcPath: string, destPath: string): Promise` ### `unzipSync(srcPath: string, destPath: string): void` 解压 zip 文件。 示例: ```ts const docs = FileManager.documentsDirectory; await FileManager.zip(docs + "/MyScript", docs + "/MyScript.zip"); await FileManager.unzip(docs + "/MyScript.zip", docs + "/Output"); ``` *** ## 其他工具方法 ### `mimeType(path: string): string` 返回文件的 MIME 类型。 ### `destinationOfSymbolicLink(path: string): string` 返回符号链接指向的目标路径。 *** ## 类型定义 ### `FileStat` ```ts type FileStat = { creationDate: number; modificationDate: number; type: string; // "file" | "directory" | "link" | "unixDomainSock" | "pipe" | "notFound" size: number; }; ``` 分享面板与快捷指令自动取得的文件授权在“更多 → 外部文件访问 → 传入文件”中按来源管理,不会新增到命名书签列表。请通过 `Intent.filesParameter` 或对应输入参数读取这些文件;需要按名字长期引用时,请使用 DocumentPicker 保存命名书签。历史命名书签仍保持可见。Agent 挂载显示用户命名及关联工作区 ID,解除挂载请在所属工作区管理。清除不可用项只移除授权记录,不删除原文件;暂时离线的授权也可能不可用,清除后需要重新授权。 --- url: /zh/guide/Changelog/3.0.0/TranslationUIProvider.md --- # TranslationUIProvider (翻译) `TranslationUIProvider` 用于接管系统翻译面板的界面展示与交互流程,让脚本自定义翻译 UI,并实现自己的默认翻译逻辑。 当宿主应用触发翻译扩展时,Scripting 会进入 `translation_ui_provider.tsx` 脚本运行环境。开发者可以在该文件中读取宿主传入的原始文本、根据需要执行翻译逻辑、构建自定义界面,并通过 `TranslationUIProvider.present(...)` 将界面呈现到当前翻译面板中。 该能力适用于以下场景: - 自定义翻译面板的界面结构与交互方式 - 在面板中展示原文、候选译文、语言切换、操作按钮等内容 - 接入自定义翻译服务或自定义翻译流程 - 在宿主允许的前提下,将译文回写替换原始文本 - 在不替换原文的情况下,仅作为查看或辅助翻译界面使用 `TranslationUIProvider` 本身不负责具体的翻译实现。它提供的是一个翻译 UI 容器与会话控制接口。真正的翻译逻辑可以由开发者在脚本中自行实现,例如调用网络接口、本地模型能力,或其他已封装的翻译模块。 *** ## 适用版本 `TranslationUIProvider` 需要 **iOS 18.4 及以上版本**。 *** ## 可用环境 `TranslationUIProvider` 仅在翻译 UI Provider 对应的运行环境中可用,开发者应在 `translation_ui_provider.tsx` 文件中使用该 API。 系统唤起翻译面板后,该脚本会作为当前翻译会话的入口执行。通常开发流程如下: 1. 读取宿主提供的原始文本 2. 根据原始文本执行默认翻译逻辑 3. 构建并展示自定义翻译界面 4. 根据用户操作决定是否扩展面板、是否结束会话、是否将译文返回给宿主 *** ## 工作机制 `TranslationUIProvider` 的核心作用可以概括为两部分: 一部分是“读取当前翻译会话上下文”,例如读取宿主传入的原始文本、判断当前是否允许替换原文。 另一部分是“控制当前翻译面板”,例如展示自定义 UI、请求系统展开面板、结束当前会话并返回译文。 脚本通常不需要主动创建会话对象。当前翻译会话由系统和宿主应用发起,Scripting 在运行 `translation_ui_provider.tsx` 时自动将当前会话能力注入到 `TranslationUIProvider` 命名空间中。 *** ## 会话输入 ### inputText ```ts const inputText: string | null ``` 表示宿主应用当前传入的原始文本。 这通常是用户在宿主应用中选中的文本,或者宿主应用希望交给翻译面板处理的文本内容。该值可能为 `null`,因此脚本在使用前应进行空值判断。 常见用途包括: - 在界面中展示待翻译原文 - 作为默认翻译逻辑的输入 - 当无可用文本时展示提示信息或禁用翻译操作 示例: ```ts const source = TranslationUIProvider.inputText if (!source) { TranslationUIProvider.present( No text available for translation. ) } ``` 需要注意的是,`inputText` 只表示当前会话启动时宿主提供的文本内容。脚本不应假设该值一定存在,也不应假设它始终可以被回写替换。 *** ### allowsReplacement ```ts const allowsReplacement: boolean ``` 表示宿主应用是否允许将译文替换回原始文本位置。 该值用于告知脚本当前会话是否具备“回写替换”能力。若为 `true`,开发者可以在用户确认后调用 `finish(translatedText)`,将译文作为结果返回给宿主;若为 `false`,即使脚本生成了译文,也通常只能用于展示,不能作为替换结果提交。 这个属性应被用于控制界面行为,例如: - 是否显示“替换原文”按钮 - 是否允许最终确认提交 - 是否仅提供“复制”或“关闭”之类的非替换操作 示例: ```ts const canReplace = TranslationUIProvider.allowsReplacement ``` 典型处理方式是,在 `allowsReplacement` 为 `false` 时,仍然可以展示翻译结果,但应避免向用户呈现会造成误解的“替换”语义按钮。 *** ## 面板控制 ### present(node) ```ts function present(node: VirtualNode): void ``` 用于将自定义脚本界面呈现到当前翻译面板中。 这是 `TranslationUIProvider` 最核心的方法。开发者应构建一个 `VirtualNode` 作为翻译面板的根界面,并通过该方法显示出来。一般来说,`translation_ui_provider.tsx` 的主要职责就是创建并展示这个 UI。 示例: ```tsx import { Text, VStack } from "scripting" TranslationUIProvider.present( Custom Translation Panel {TranslationUIProvider.inputText ?? "No input text"} ) ``` 通常建议将整个翻译面板的 UI 组织为一个独立的函数组件,再传给 `present(...)`,这样更便于维护和扩展。 例如: ```tsx function TranslationView() { const source = TranslationUIProvider.inputText return Original {source ?? "No input text"} } TranslationUIProvider.present() ``` `present(...)` 只负责显示脚本 UI,不会自动结束会话,也不会自动将译文返回给宿主。界面中的具体交互流程,仍需要开发者在脚本中自行实现。 *** ### expandSheet() ```ts function expandSheet(): void ``` 请求系统将当前翻译面板展开。 翻译面板在系统中可能以较紧凑的状态出现。调用 `expandSheet()` 可以向系统表达“当前 UI 需要更大展示空间”的意图,例如在以下情况中会比较合适: - 需要展示较长原文和较长译文 - 需要展示多段候选结果 - 需要展示更多操作控件或设置项 - 用户主动点击“展开”或“查看更多” 示例: ```ts TranslationUIProvider.expandSheet() ``` 需要注意,这个方法是对系统的一次请求,具体是否展开以及如何展开,仍由系统决定。脚本应将其理解为“请求更大的面板展示空间”,而不是保证立即进入某种固定尺寸。 *** ### finish(translation?) ```ts function finish(translation?: string | null): void ``` 结束当前翻译会话,并可选择将译文返回给宿主应用。 这是翻译面板流程的结束点。调用后,当前会话会关闭。 它有两种典型使用方式。 第一种是不返回译文,仅关闭面板: ```ts TranslationUIProvider.finish() ``` 这种方式适用于: - 用户取消操作 - 当前仅做浏览,不做替换 - 当前宿主不允许回写替换 - 翻译失败后直接关闭 第二种是返回译文并结束会话: ```ts TranslationUIProvider.finish("Hello world") ``` 这种方式通常用于用户确认使用某个译文作为最终结果时。只有在宿主允许替换的情况下,这样的结果才有实际意义。因此在调用前,通常应结合 `allowsReplacement` 做判断。 示例: ```ts if (TranslationUIProvider.allowsReplacement) { TranslationUIProvider.finish(translatedText) } else { TranslationUIProvider.finish() } ``` 需要注意以下几点: - `finish(...)` 调用后,会话即结束,通常不应继续更新当前 UI - 传入字符串表示希望将该字符串作为翻译结果返回给宿主 - 传入 `null` 或省略参数表示仅关闭会话,不执行替换 - 是否真正替换原文,最终取决于宿主和系统当前会话能力,而不是脚本单方面决定 *** ## 推荐的开发模式 在 `translation_ui_provider.tsx` 中,推荐采用“初始化数据 + 展示界面 + 用户确认后结束会话”的结构。 典型流程如下: 1. 读取 `TranslationUIProvider.inputText` 2. 如果没有原始文本,展示不可操作状态 3. 如果有原始文本,执行默认翻译逻辑 4. 将原文、译文、操作按钮等显示在 UI 中 5. 用户确认后,根据 `allowsReplacement` 决定是否调用 `finish(translatedText)` 6. 若用户取消,则调用 `finish()` 或 `finish(null)` *** ## 示例:最小可用翻译面板 下面示例展示一个最基础的翻译面板,它读取原文并展示简单 UI。 ```tsx import { Button, Text, VStack } from "scripting" function TranslationView() { const source = TranslationUIProvider.inputText return Original Text {source ?? "No text available"} ))}
) } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/Changelog/3.1.0/AVCaptureSession & Camera Control/Live Photo/index.md --- # Live Photo 实况照片 Live Photo 是一张照片 + 拍照前后短短一段 `.mov`。`AVCapturePhotoOutput` 让你**按次**决定要不要拍——在 `capturePhoto` 时传 `livePhotoMovieFile`,resolve 出来同时包含静态图和 movie 文件路径。 ## 前置条件 - `isLivePhotoCaptureSupported === true`(所有有相机的 iPhone 都满足)。 - 一次性把开关打开: `photoOutput.isLivePhotoCaptureEnabled = true`。不支持的设备 setter 会静默 clamp 回 `false`,简单方法是写完再读一次确认。 - 调 `capturePhoto({ livePhotoMovieFile, ... })` 时 `isLivePhotoCaptureEnabled` 必须是 `true`,否则 promise **立即 reject** 而不是退化成普通拍照。 - **不要**同时开 `isAutoDeferredPhotoDeliveryEnabled`。deferred 开启后系统可能不产 `.mov`,resolve 出来的 `livePhotoMovieFileURL` 会缺失。 ## 接线 ```ts const camera = AVCaptureDevice.default("video")! const session = new AVCaptureSession() const photoOutput = new AVCapturePhotoOutput() session.configure(() => { session.sessionPreset = "photo" session.addInput(new AVCaptureDeviceInput(camera)) session.addOutput(photoOutput) }) // 一次性配置,跨多次 capturePhoto 都生效。 photoOutput.isLivePhotoCaptureEnabled = true await session.startRunning() const ts = Date.now() const photoFile = `${FileManager.documentsDirectory}/live_${ts}.heic` const movieFile = `${FileManager.documentsDirectory}/live_${ts}.mov` const result = await photoOutput.capturePhoto({ codec: "hevc", photoFile, // ← 后面要存进系统照片库的话, 必传 livePhotoMovieFile: movieFile, livePhotoVideoCodec: "hevc", }) console.log("photo:", result.image.width, "×", result.image.height) console.log("still file:", result.photoFileURL) console.log("movie:", result.livePhotoMovieFileURL) ``` Resolve 出的对象除了标准的 `image / metadata / isRawPhoto / isDeferredProxy`,多 `photoFileURL: string`(传了 `photoFile` 时)和 `livePhotoMovieFileURL: string`(传了 `livePhotoMovieFile` 时)。没要 Live Photo,`.mov` 字段不出现。 ### 为什么 Live Photo 必须用 `photoFile` `capturePhoto` 总会给你 `result.image: UIImage` —— 但 `UIImage` 是已经解码的位图,**没有**原始 metadata。把 Live Photo 存进系统照片库时,`Photos.saveLivePhoto(...)` 内部走 PhotoKit,PhotoKit 会校验 still 和 `.mov` 共享一个 Live Photo asset identifier(写在 still 的 Apple Maker Note key 17、`.mov` 的 `com.apple.quicktime.content.identifier`)。用 `image.toJPEGData()` 重编码出的 JPEG **没有**这个 identifier,PhotoKit 会拒绝配对并报 **`PHPhotosErrorDomain 3302`**。 `photoFile` 选项让 bridge 把 `photo.fileDataRepresentation()` 原始 bytes 直接写到磁盘,Maker Note 完整保留。把 `result.photoFileURL` 喂给 `Photos.saveLivePhoto({ imagePath, videoPath })`,配对就通了。 ## resolve 实际在等什么 Live Photo 触发两路并行 AVFoundation 回调:一路给静态图、一路给 `.mov`。bridge 等**两路都到齐**才 resolve——保证拿到完整一对,或者拿到错误。AVFoundation 不保证两者的回调顺序,所以**别用文件时间戳推断顺序**。 系统会在最后跑一个"capture finish"统一收尾。如果中途某一路出问题(比如 `.mov` 被丢),bridge 会用已到达的部分兜底 resolve,不会把 promise 吊死。 ## 路径规则 - 必须传**绝对路径**,以 `.mov` 结尾。`${FileManager.documentsDirectory}/...` 是最常用的可写位置。 - AVFoundation 拒绝向已存在的路径写。bridge 在拍照前**自动删除**目标路径的旧文件,免得你手动 cleanup。 - `.mov` 不大(1.5 秒大约 2–4 MB)。连拍场景请自己清理旧文件。 ## 编码选择 `livePhotoVideoCodec` 可选: - `"hevc"` — iPhone 7 起的设备首选,文件更小。 - `"h264"` — 兼容性更好(老系统、部分剪辑工具)。 如果传了设备不在 `availableLivePhotoVideoCodecTypes` 列表里的 codec,bridge 让 AVFoundation 自己挑默认,不会让 capture 整个失败。需要确认实际写入了什么,用 `AVAsset` 打开读 track 信息即可。 ## 注意 - Live Photo + `flashMode = "on"` 可以用,但拍下来的 `.mov` 会带闪光闪烁,设计时考虑。 - 你拿到的 `.mov` 跟 Photos.app 拍下来的一样,会有快门前后短短一段预滚 / 后滚。 - `capturePhoto` 只把文件写到磁盘,**不会**自动入系统照片库。要把图 + clip 作为关联 Live Photo 存进 Photos(像 Camera.app 那样),用 [`Photos.saveLivePhoto`](#): ```ts await Photos.saveLivePhoto({ imagePath: result.photoFileURL!, // 用 photoFile 选项写盘的原始 HEIC videoPath: result.livePhotoMovieFileURL!, // livePhotoMovieFile 选项写盘的 .mov shouldMoveFile: true, // 两个文件 move 进 Photos,而不是 copy }) ``` 这会把两份资源配对成一个 PHAsset,Photos.app 长按会有 "Live" 动画。首次调用时系统自动弹照片库权限授权。**千万不要**把 `result.photoFileURL` 换成 `result.image.toJPEGData()` 写盘的结果 —— 重编码出的 JPEG 没有 Live Photo asset identifier, PhotoKit 会拒绝配对。 ## 手上只有视频、没有相机? 如果素材是文件而不是实时拍摄——录屏、下载的片段、相册里的视频——根本不需要 capture session。`LivePhoto.createFromVideo(...)` 能从任意本地视频生成合规资源对,见《把视频变成实况照片》一页。 --- url: /zh/guide/Changelog/3.1.0/AVCaptureSession & Camera Control/Live Photo/index_example.md --- # 示例 ```tsx import { Button, CaptureVideoPreviewView, HStack, Image, Navigation, NavigationStack, Script, Spacer, Text, Toolbar, ToolbarItem, useEffect, useMemo, useObservable, VStack } from "scripting" type Shot = { index: number image: UIImage photoSize: string /** native 写盘的原始 still bytes(HEIC/JPEG),含 Live Photo asset identifier */ photoURL?: string movieURL?: string movieSize?: number ms: number isDeferredProxy: boolean } function View() { const dismiss = Navigation.useDismiss() const isRunning = useObservable(false) const shots = useObservable([]) const captureCount = useObservable(0) const lastError = useObservable("") const livePhotoSupp = useObservable(false) const livePhotoEn = useObservable(false) const { session, camera, photoOutput } = useMemo(() => { const camera = AVCaptureDevice.default("video")! const session = new AVCaptureSession() const input = new AVCaptureDeviceInput(camera) const photoOutput = new AVCapturePhotoOutput() session.configure(() => { session.sessionPreset = "photo" if (session.canAddInput(input)) session.addInput(input) if (session.canAddOutput(photoOutput)) session.addOutput(photoOutput) }) // 必须在 addOutput 之后查 supported,在那之前 photoOutput 没绑 session 时 supported=false。 return { session, camera, photoOutput } }, []) useEffect(() => { async function start() { try { await session.startRunning() isRunning.setValue(true) // Live Photo 必须开启 enabled 之后才会真正生效。 photoOutput.isLivePhotoCaptureEnabled = true // 读回真实值: 不支持的设备 setter 会被 clamp 回 false。 livePhotoSupp.setValue(photoOutput.isLivePhotoCaptureSupported) livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) console.log("[startRunning]", { preset: session.sessionPreset, liveSupp: photoOutput.isLivePhotoCaptureSupported, liveEn: photoOutput.isLivePhotoCaptureEnabled, }) } catch (e) { await Dialog.alert({ message: `Failed to start: ${String(e)}` }) dismiss() } } start() return () => { session.stopRunning().finally(() => session.dispose()) } }, []) async function takeLivePhoto() { const idx = captureCount.value + 1 captureCount.setValue(idx) const ts = Date.now() // 同时让 native 写盘 still + .mov。两份文件共享 Apple Maker Note 里的 // Live Photo asset identifier, Photos.saveLivePhoto 才能 pair 上。 const photoFile = `${FileManager.documentsDirectory}/live_${idx}_${ts}.heic` const movieFile = `${FileManager.documentsDirectory}/live_${idx}_${ts}.mov` const start = Date.now() try { const result = await photoOutput.capturePhoto({ codec: "hevc", photoFile, livePhotoMovieFile: movieFile, livePhotoVideoCodec: "hevc", }) const ms = Date.now() - start // 读 movie 文件大小供 UI 显示 let movieSize: number | undefined if (result.livePhotoMovieFileURL) { try { const stat = await FileManager.stat(result.livePhotoMovieFileURL) movieSize = stat.size } catch { /* ignore */ } } shots.setValue([{ index: idx, image: result.image, photoSize: `${result.image.width}×${result.image.height}`, photoURL: result.photoFileURL, movieURL: result.livePhotoMovieFileURL, movieSize, ms, isDeferredProxy: result.isDeferredProxy, }, ...shots.value].slice(0, 6)) lastError.setValue("") } catch (e) { lastError.setValue(String(e)) } } /** 不开 Live Photo,验证退化路径:resolve 不应包含 livePhotoMovieFileURL */ async function takeRegular() { const idx = captureCount.value + 1 captureCount.setValue(idx) const start = Date.now() try { const result = await photoOutput.capturePhoto({ codec: "hevc" }) shots.setValue([{ index: idx, image: result.image, photoSize: `${result.image.width}×${result.image.height}`, movieURL: result.livePhotoMovieFileURL, // 应为 undefined ms: Date.now() - start, isDeferredProxy: result.isDeferredProxy, }, ...shots.value].slice(0, 6)) lastError.setValue("") } catch (e) { lastError.setValue(String(e)) } } /** * 把最新一张 Live Photo 配对存进系统照片库。 * 关键: `imagePath` 必须用 native 写盘的 `result.photoFileURL`(原始 HEIC, * 含 Apple Maker Note 里的 Live Photo asset identifier),用 toJPEGData 重编码 * 出来的 JPEG 会丢这个 identifier, Photos.saveLivePhoto 报 PHPhotosError 3302。 * `shouldMoveFile: true` 会把磁盘上两个文件 move 进 Photos,本地副本就消失了。 */ async function saveLast() { const last = shots.value[0] if (!last) { lastError.setValue("Capture a Live Photo first") return } if (!last.photoURL || !last.movieURL) { lastError.setValue("Last capture missing photoURL or movieURL (was it a Regular shot?)") return } try { await Photos.saveLivePhoto({ imagePath: last.photoURL, videoPath: last.movieURL, shouldMoveFile: true, }) lastError.setValue(`Saved Live Photo #${last.index} to Photos library`) } catch (e) { lastError.setValue(`Save failed: ${String(e)}`) console.error(e) } } /** 故意关掉 enabled 再调 Live Photo,期望 promise reject */ async function probeReject() { photoOutput.isLivePhotoCaptureEnabled = false livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) try { await photoOutput.capturePhoto({ livePhotoMovieFile: `${FileManager.documentsDirectory}/should_reject.mov`, }) lastError.setValue("Unexpected: did not reject") } catch (e) { lastError.setValue(`OK (rejected): ${String(e)}`) } finally { // 恢复 enabled 方便继续测 photoOutput.isLivePhotoCaptureEnabled = true livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) } } return ( })} {resp != null ? <> : <> } {/* 未选中的先画(细),选中的最后画压在上面(粗)。MapPolyline 目前不接收 opacity / 视图层 modifier,这里用 stroke width(3 vs 6)制造主次对比。 */} {routes.map((r, i) => { if (i === selectedIdx) return null return })} {routes[selectedIdx] != null ? : null} } // ─────────────────────────────────────────────────────────────────────── // Demo 4: calculateETA — time / distance only, no geometry download // ─────────────────────────────────────────────────────────────────────── function ETADemo() { type Mode = "automobile" | "walking" const [mode, setMode] = useState("automobile") const [eta, setEta] = useState(null) const [loading, setLoading] = useState(false) const [err, setErr] = useState(null) const calc = async () => { setLoading(true); setErr(null) try { const result = await MapDirections.calculateETA({ source: { coordinate: PEOPLES_SQUARE, name: "People's Square" }, destination: { coordinate: LUJIAZUI, name: "Lujiazui" }, transportType: mode, departureDate: new Date(), }) setEta(result) } catch (e) { setErr(String(e)) } finally { setLoading(false) } } return 4. `calculateETA` Skip the polyline download; get back travel time / distance / arrival window only. Cheaper than `calculate` when the UI just needs a headline number. setMode(v as Mode)} pickerStyle={"segmented"} > automobile walking ) ``` 在 **编辑小组件** 中,将需要执行的动作添加为第一、第二个条目。排序或删除会改变后续条目的索引,请相应调整按钮标签或配置顺序。 `Widget.shortcutCount` 返回已配置条目的数量。例如,可以为每个条目生成一个按钮: ```tsx Widget.present( {Array.from({ length: Widget.shortcutCount }, (_, index) => ( ) ``` 在 **编辑小组件** 中,将需要执行的动作添加为第一、第二个条目。排序或删除会改变后续条目的索引,请相应调整按钮标签或配置顺序。 `Widget.shortcutCount` 返回已配置条目的数量。例如,可以为每个条目生成一个按钮: ```tsx Widget.present( {Array.from({ length: Widget.shortcutCount }, (_, index) => ( )} } } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/Changelog/3.2.2/Menu Action Dismissal.md --- # 菜单操作后的关闭行为 Scripting 提供的 `Menu` 是一个交互式菜单组件,用于展示一组操作项或子菜单。该组件可以作为操作容器,也支持嵌套结构,适合在工具栏、上下文菜单或紧凑布局中统一管理多个相关操作。 其行为类似于 SwiftUI 中的 `Menu`,支持纯文本标签和自定义视图标签,并可配置点击时的默认行为。 *** ## 用途 使用 `Menu` 可以将多个相关操作整合为一个统一入口,提升界面整洁性与可用性。菜单中可以包含多个 `Button` 组件,也可以嵌套其他 `Menu` 实现多级菜单结构。 *** ## 属性定义 ```ts type MenuProps = { primaryAction?: () => void children?: VirtualNode | (VirtualNode | undefined | null)[] } & ( | { title: string systemImage?: string } | { label: VirtualNode } ) ``` ### 基础属性 | 属性名 | 类型 | 说明 | | --------------- | ----------------- | ---------------------------------- | | `primaryAction` | `() => void`(可选) | 点击菜单本身时触发的主操作,不展开子菜单。适合设置默认行为。 | | `children` | `VirtualNode` 或数组 | 菜单的内容,通常是 `Button` 或嵌套的 `Menu` 组件。 | ### 标签配置(二选一) 开发者必须指定以下两种标签方式之一: #### 方式一:`title` 与可选的 `systemImage` | 属性名 | 类型 | 说明 | | ------------- | ------------ | ----------------------- | | `title` | `string` | 菜单标题,描述菜单的操作内容。 | | `systemImage` | `string`(可选) | SF Symbols 图标名称,显示在标题旁。 | #### 方式二:`label` 自定义视图标签 | 属性名 | 类型 | 说明 | | ------- | ------------- | -------------------- | | `label` | `VirtualNode` | 自定义菜单标签视图,可组合图标、文本等。 | *** ## 示例:基础菜单结构 ```tsx ``` 在此示例中: - 主菜单为 `"操作"`,包含两个按钮和一个嵌套的 `"复制"` 子菜单; - 子菜单中继续包含两个按钮。 *** ## 示例:使用 `primaryAction` 和图标 ```tsx console.log("点击菜单")} > ``` - 用户点击菜单图标将触发 `primaryAction`; - 长按或展开菜单时,会展示其 `children` 内容。 *** ## 示例:使用自定义标签 ```tsx 选项 } > ``` 此示例使用 `HStack` 组合图标与文本作为菜单标签,适合在复杂场景下灵活布局。 *** ## 开发提示 - `Menu` 常用于 `toolbar`、`contextMenu` 等需要组合多个操作的界面中; - 可无限嵌套子菜单,构建多层级操作结构; - 若操作不多且用户期望直接执行某一默认行为,可设置 `primaryAction`; - 自定义 `label` 可用于图标+文本的混合样式,提升可视性与品牌一致性。 *** ## 菜单操作后的关闭行为(iOS 16.4+) `menuActionDismissBehavior?: "automatic" | "enabled" | "disabled"` 控制执行菜单操作后是否关闭菜单。`automatic` 使用系统默认行为,`enabled` 关闭菜单,`disabled` 保持菜单打开。可设置在某个菜单操作上,只让该操作保留菜单;也可设置在提供菜单的控件上,例如 menu 样式的 Picker。上下文菜单同样支持。 直接 props 与 `modifiers().menuActionDismissBehavior(...)` 等价,旧系统忽略此偏好。它不会新增操作或修改标签。保持明确的关闭途径,并检查重复执行操作后的 VoiceOver 焦点。 ```tsx ``` --- url: /zh/guide/Changelog/3.2.2/Native Touch Events for Custom Keyboards/index.md --- # onTouchGesture:原生触摸事件 `onTouchGesture` 在 **iOS 18+** 通过 UIKit 获取每根手指的触摸阶段。适合自定义键盘的按键或整行专用触摸区,SwiftUI 继续负责布局,脚本判断点按、长按和划动。它是可选的新路径,不会自动改变 `DragGesture`。iOS 17 忽略此属性,不安装替代手势;旧系统兼容路径须由脚本明确选择。 ```tsx import { Text, modifiers, type TouchGestureEvent } from "scripting" function receive(event: TouchGestureEvent) { switch (event.phase) { case "began": /* 按 startLocation 命中,锁定 touchId,显示按下状态。 */ break case "moved": /* 更新匹配手指的位移/意图。 */ break case "ended": /* 提交一次,释放匹配的手指。 */ break case "cancelled": /* 清高亮、弹窗和定时器;不能提交点按。 */ break } } const direct = 按键 const chained = 按键 ``` ## 属性 ```ts type TouchGestureProps = { enabled?: boolean // 默认 true,false 取消活跃触摸 coordinateSpace?: "local" // 默认 local,目前只支持 local onEvent: (event: TouchGestureEvent) => void } ``` 回调同步运行,应保持简短。不要等待 Promise 或逐事件同步写盘。主线程/JS 阻塞仍会影响响应,本接口不保证延迟上限。 ## 事件字段 | 字段 | 含义 | | --------------- | ------------------------------------------------------------------------------------------------------- | | `touchId` | 触摸唯一字符串 ID;同一手指从 began 到结束保持不变,下次触摸不复用 | | `sequence` | 同一绑定区域内递增的事件序号,不是手指编号 | | `phase` | `began`、`moved`、`ended`、`cancelled` | | `startLocation` | 初始 `{ x, y }`,绑定 SwiftUI 视图的 local 坐标,单位 point | | `location` | 当前 local 位置 `{ x, y }`,单位 point | | `translation` | 当前位置减初始位置 `{ width, height }`,单位 point | | `velocity` | `{ width, height }`,point/s;使用事件时间差分与 30ms 指数低通,began 为零 | | `timestamp` | UIKit 事件时间,系统 uptime 毫秒,不是 Unix 时间 | | `receivedAt` | 原生接收时间,与 timestamp 同源的 uptime 毫秒 | | `dispatchAt` | 原生调用 JS 前的时间,与 timestamp 同源的 uptime 毫秒 | | `reason` | 可选取消原因,例如 `system`、`reset`、`disabled`、`removed`、`keyboardHidden`、`scriptSwitched`、`scriptExited`;不是固定枚举 | `receivedAt - timestamp` 观察事件投递等待,`dispatchAt - receivedAt` 观察原生处理到 JS 调用前的等待,均不是画面呈现延迟。合成取消事件的 timestamp 为取消时刻。不能直接与 `Date.now()` 或未校准的 `performance.now()` 相减。 不提供 `predictedEndLocation` / `predictedEndTranslation`,速度也不保证与 SwiftUI 估计相同。依赖速度/预测来取消长按的脚本需要适配和验证启发式,不应伪造预测字段。 ## 归属、取消与兼容 逐指保存 touchId 状态。单指状态机可以采用“第一根持有,其他手指整段忽略”,不能让第二根手指提交/结束第一根。整行通过初始位置命中扩大的按键区域,移动后仍保留初始目标。 初始触点按绑定视图的 local 布局矩形过滤,不提供任意 contentShape 或额外 hitSlop 的等价语义。需要扩大的命中区域时,先扩大专用触摸视图的实际 frame。 禁用、视图移除、系统取消和键盘隐藏/切换会取消活跃触摸。取消时停止长按、删除和光标 repeat,清理 popup/highlight,**不要调用提交点按的 end/settle**。脚本退出后不应依赖还能收到 JS 回调;组件 cleanup 也须清理计时器和状态。 该接口不是 `GestureInfo`,不接受 `GestureMask`,不能传入 `gesture`、`highPriorityGesture` 或 `simultaneousGesture`。它保留布局,但不保证与子级按钮、滚动和菜单的手势竞争关系等价。仅绑定专用输入区;整行与单键不要重叠,同一区域不要同时安装旧拖动路径。候选滚动、contextMenu、工具栏及系统键盘切换保留原交互。 完整多指输入还需要脚本隔离长按、repeat、光标等共享状态;增加此接口不等于单指键盘自动支持多指。保留显式回退开关,切换前取消活跃手势。 触摸取消时的位置为最后一个可靠位置;取消事件不会读取正在移除的视图几何信息。每根手指最多收到一个终止事件。请将 `cancelled` 用于清理按下状态,而不要提交按键动作。 --- url: /zh/guide/Changelog/3.2.2/Native Touch Events for Custom Keyboards/index_example.md --- # 示例 ```tsx import { Navigation, NavigationStack, Script, Text, VStack, modifiers, useState, type TouchGestureEvent } from "scripting" function Example() { const [status, setStatus] = useState("Touch either surface") function receive(event: TouchGestureEvent) { setStatus(`${event.phase} ${event.touchId.slice(-6)}\n` + `x=${event.location.x.toFixed(1)} y=${event.location.y.toFixed(1)}\n` + `native delivery=${(event.receivedAt - event.timestamp).toFixed(1)}ms`) } return {status} JSX touch surface Chained touch surface iOS 18+. This example updates every event; use buffered sampling for performance tests. } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Bordered Text Inputs.md --- # 带边框文本输入 通过该属性,你可以定义文本框的视觉样式,从而影响其边框、背景和布局的外观。不同的样式可以帮助文本框在各种 UI 设计中无缝融合,或提供功能上的提示。 *** ## 概述 `TextField` 为用户提供了一个输入文本的方式。通过选择 `textFieldStyle`,你可以决定文本框是以简洁、无边框的样式呈现,还是以更加明显的圆角边框显示,从而突出输入区域。 *** ## 可用样式 - **`automatic`**:\ 让系统根据平台和上下文选择合适的样式。如果没有明确的样式偏好,这是一个方便的默认选择。 - **`plain`**:\ 以最少的装饰显示文本框。这种样式通常看起来像纯文本,适合不希望输入框过于显眼的布局。 - **`roundedBorder`**:\ 为文本框添加一个圆角矩形边框。这种样式能让输入区域更加突出,清楚地表明用户可以在其中输入内容。适合用于表单或需要用户进行主要操作的场景。 *** ## 基本用法 以下示例展示了如何使用具有特定样式的 `TextField`: ```tsx setUsername(newVal)} textFieldStyle="roundedBorder" prompt="输入您的用户名" /> ``` 在此示例中,`textFieldStyle="roundedBorder"` 会用视觉效果突出输入框,让用户明确知道可以点击并输入。 *** ## 其他常用属性 - **`value: string`**:\ 文本框当前的内容。用户输入时更新该值以保持显示内容同步。 - **`onChanged: (value: string) => void`**:\ 每当文本框内容更改时调用的回调函数,可用于响应用户输入。 - **`prompt?: string`**:\ 提示或占位符文本,用于指导用户输入内容。 - **`axis?: Axis`**:\ 决定当文本超出显示范围时的滚动方向。如果预期用户输入的内容较长,可以使用此属性。 - **`autofocus?: boolean`** _(默认值: false)_:\ 如果设置为 `true`,文本框会在显示时自动获得焦点,方便用户立即输入。 - **`onFocus?: () => void` 和 `onBlur?: () => void`**:\ 分别在文本框获得或失去焦点时调用的回调函数,可用于提供视觉反馈、执行验证或更新其他 UI 部分。 *** ## 示例 ```tsx 邮箱:} value={email} onChanged={setEmail} prompt="you@example.com" textFieldStyle="plain" autofocus={true} onFocus={() => console.log('获得焦点')} onBlur={() => console.log('失去焦点')} /> ``` 在此示例中,文本框被设置为 `plain` 样式,与周围内容更融为一体。`autofocus` 属性确保用户在进入此视图后可以立即开始输入。 *** ## 总结 通过 `textFieldStyle`,你可以根据不同的上下文调整输入框的外观。无论是选择低调的 `plain` 样式,还是选择更加结构化的 `roundedBorder` 样式,合适的样式能够帮助创建清晰、直观的用户体验。如果不确定样式选择,可以使用 `automatic` 让系统决定最合适的外观。 *** ## iOS 27 带边框输入框 `textFieldStyle="bordered"` 使用新的带边框输入框样式。可搭配 `textInputBorderShape="automatic"`、`"capsule"` 或 `"roundedRectangle"` 控制边框形状,两者均支持视图属性和链式 modifiers。 ```tsx ``` iOS 27 之前,`bordered` 降级为 `roundedBorder`,忽略 `textInputBorderShape`。 --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Concentric Corner Geometry.md --- # 同心圆角几何信息 `GeometryReader` 是 Scripting 中与 SwiftUI 等效的几何布局读取组件。 它能够在视图构建阶段提供当前容器的尺寸、边距、安全区域和角落内边距等信息,使开发者可以根据环境动态布局内容。 当你需要根据父容器的大小进行自适应布局(响应式布局)时,`GeometryReader` 是非常重要的工具。 *** ## GeometryProxy 当 `GeometryReader` 构建其子内容时,会将一个 `GeometryProxy` 实例传递给 `children` 回调。开发者可以使用此对象访问与当前容器相关的布局信息。 ```ts interface GeometryProxy { readonly size: Size; readonly safeAreaInsets: { leading: number; top: number; trailing: number; bottom: number; }; /** * Requires iOS 26.0+. */ readonly containerCornerInsets: { bottomLeading: Size; bottomTrailing: Size; topLeading: Size; topTrailing: Size; } | null; } ``` *** ## GeometryProxy 属性说明 ## 1. size ```ts readonly size: Size ``` 当前容器在布局时的实际尺寸。 ### Size 结构 ```ts type Size = { width: number height: number } ``` ### 示例 ```tsx proxy.size.width proxy.size.height ``` 用于动态计算子视图布局,例如宽高比、自适应排版等。 *** ## 2. safeAreaInsets ```ts readonly safeAreaInsets: { leading: number top: number trailing: number bottom: number } ``` 当前视图所处环境中的安全区域内边距,包括顶部、底部、左右侧的避让区域。 通常用于避免内容被刘海、Home Indicator 等遮挡。 ### 示例用途: - 内容距离屏幕底部安全区域以上对齐 - 自定义导航栏、工具栏时避免被遮挡 - 实现与设备 UI 边界一致的响应式布局 *** ## 3. containerCornerInsets(iOS 26.0+) ```ts readonly containerCornerInsets: { bottomLeading: Size bottomTrailing: Size topLeading: Size topTrailing: Size } | null ``` 该属性仅在 **iOS 26+** 提供,并在设备或容器具有物理圆角偏移时报告每个角落的内边距。 ### 用途 - 为圆角窗口、Stage Manager 或分屏环境适配布局 - 在容器圆角内做精确的 UI 对齐 如果平台不支持,则为 `null`。 *** ## GeometryReader ```ts type GeometryReaderProps = { children: (proxy: GeometryProxy) => VirtualNode; }; declare const GeometryReader: FunctionComponent; ``` ## Props 说明 | 属性名 | 类型 | 必须 | 说明 | | -------- | --------------------------------------- | -- | -------------------------------------- | | children | `(proxy: GeometryProxy) => VirtualNode` | 是 | 构建内容的回调函数,传入 `GeometryProxy` 用于读取布局信息。 | *** ## 工作机制 1. GeometryReader 占据父布局中的位置,并在布局阶段获取当前容器的尺寸与安全区域信息。 2. 将 `GeometryProxy` 注入给 `children(proxy)` 回调。 3. 回调返回的内容将根据读取的信息动态布局。 与 SwiftUI 一样,`GeometryReader` 默认会扩展到可用空间。 *** ## 示例:居中布局 ```tsx import { GeometryReader, Text, VStack } from "scripting" function View() { return {(proxy) => { return Hello Geometry width: {proxy.size.width} height: {proxy.size.height} }} } ``` *** ## 示例:根据安全区域调整布局 ```tsx {(proxy) => { return Content inside safe area. }} ``` *** ## 示例(iOS 26+):读取 containerCornerInsets ```tsx {(proxy) => { const corners = proxy.containerCornerInsets return {corners == null ? "Corner insets not available" : `Top Leading Corner: ${corners.topLeading.width}, ${corners.topLeading.height}` } }} ``` *** ## 使用建议 - 在需要响应容器尺寸时使用 GeometryReader,例如图片缩放、动态布局、等比布局。 - 避免将大量复杂布局放入 GeometryReader 内,可能影响性能(同 SwiftUI)。 *** ## 同心圆角半径(iOS 27.0+) `proxy.concentricCornerRadii` 返回 `{ topLeading, bottomLeading, bottomTrailing, topTrailing }`,单位是 point,表示当前几何布局适用的同心矩形圆角半径。旧系统或 SwiftUI 没有圆角信息时为 `null`。它是布局快照,随 `size` 和 `safeAreaInsets` 一起更新,不保留原生 GeometryProxy,也不提供任意 frame 查询。 *** ## 预留区域(iOS 27.1+) `proxy.reservedRegions(kind, options?)` 返回 `kind: "occlusion" | "division"` 的布局快照。每个 ReservedRegion 包含 kind、frame(`{ x, y, width, height }`)、margins(`{ top, bottom, leading, trailing }`)、isActive。frame 使用 GeometryReader 的本地坐标,单位为 point;旧系统返回空数组。 默认两个 kind 都查询当前活动区域,并使用镜像布局方向。非默认查询应先在 `GeometryReader.reservedRegionQueries` 中声明,再使用相同选项调用 reservedRegions。选项为 `includeInactive?: boolean` 和 `layoutDirectionBehavior?: "fixed" | "mirrors" | { mirrors: "leftToRight" | "rightToLeft" }`。调用未声明的非默认查询会抛错。区域和 frame 都是当前布局构建的快照,保留 proxy 不会得到持续更新的对象。 可据此避免将控件放在折痕或遮挡区域下,同时保留正确阅读顺序和常见任务的操作入口。支持此 API 的系统上也可能返回空数组。 ```tsx {proxy => {proxy.reservedRegions("division", { includeInactive: true }).length} division regions} ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Cross-Fade Navigation Transition.md --- # 淡入淡出导航转场 Scripting App 提供了一组用于配置导航行为的视图修饰符,允许开发者控制页面标题的展示内容与样式,并自定义返回按钮的显示与否。这些修饰符与 SwiftUI 中的导航系统高度一致,适用于导航栈中的任意视图。 *** ## `navigationTitle` ```ts navigationTitle?: string ``` 设置当前视图在导航栏中显示的标题。 ### 说明 - 在 **iOS** 中,当视图被嵌套在导航栈中时,所设置的标题将显示在导航栏中。 - 在 **iPadOS** 中,主导航目的地的标题也会在多任务切换界面中显示为窗口的标题。 *** ## `navigationBarTitleDisplayMode` ```ts navigationBarTitleDisplayMode?: NavigationBarTitleDisplayMode ``` 设置导航栏标题的展示样式。 ### 枚举类型:`NavigationBarTitleDisplayMode` ```ts type NavigationBarTitleDisplayMode = "automatic" | "large" | "inline" ``` - **`automatic`**:系统根据上下文自动选择合适的标题样式。 - **`large`**:以大标题样式显示,通常用于导航栈的根视图。 - **`inline`**:将标题与导航栏控件同行显示,采用紧凑布局。 *** ## `navigationBarBackButtonHidden` ```ts navigationBarBackButtonHidden?: boolean ``` 控制是否隐藏默认的导航栏返回按钮。 ### 说明 - 设为 `true` 时,系统将不显示默认的返回按钮。 - 适用于需要自定义返回行为,或禁止用户返回的界面场景。 *** ## 示例 ```tsx 欢迎来到个人资料页面 ``` 在该示例中: - 设置视图标题为 `"个人资料"`,并展示在导航栏中。 - 标题采用 `inline` 紧凑样式。 - 默认的返回按钮被隐藏。 *** ## iOS 27 淡入淡出转场 `navigationTransition="crossFade"` 使用系统淡入淡出导航转场,要求 iOS 27.0+;旧系统使用 `automatic`。已有 `zoom` 配置继续可用。 --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Dismissal Confirmation.md --- # 关闭确认弹窗 Scripting App 提供了对 SwiftUI 风格的模态视图展示的支持。开发者可以通过向组件声明特定的属性,实现类似 `sheet`、`popover`、`fullScreenCover`、`alert` 和 `confirmationDialog` 的展示行为。这些展示是响应状态变化的,并支持多种配置项,以满足在不同屏幕尺寸和交互需求下的使用场景。 *** ## Alert(警告弹窗) 当条件为真时,展示一个带标题、可选消息和操作按钮的警告弹窗。 ```ts alert?: { title: string isPresented: boolean onChanged: (isPresented: boolean) => void actions: VirtualNode message?: VirtualNode } ``` ### 字段说明 - **`title`**:弹窗的标题文本。 - **`isPresented`**:控制弹窗是否显示的布尔值。 - **`onChanged`**:当 `isPresented` 状态变化时调用的回调函数。需要在用户关闭弹窗时将其更新为 `false`。 - **`actions`**:表示操作按钮的 `VirtualNode`。 - **`message`**(可选):用于展示附加信息的 `VirtualNode`。 *** ## Confirmation Dialog(确认对话框) 展示一个确认对话框,包含标题、可选消息和操作项。 ```ts confirmationDialog?: { title: string titleVisibility?: Visibility isPresented: boolean onChanged: (isPresented: boolean) => void actions: VirtualNode message?: VirtualNode } ``` ### 字段说明 - **`title`**:对话框的标题。 - **`titleVisibility`**(可选):标题是否显示,默认值为 `"automatic"`。 - **`isPresented`**:是否显示对话框。 - **`onChanged`**:用于更新 `isPresented` 状态的回调。 - **`actions`**:对话框操作项。 - **`message`**(可选):附加消息内容。 ```ts type Visibility = "automatic" | "hidden" | "visible" ``` *** ## Sheet(底部弹窗) 从底部弹出模态视图,通常用于展示中等重要性的内容。支持传入单个或多个配置项。 ```ts sheet?: ModalPresentation | ModalPresentation[] ``` *** ## Full Screen Cover(全屏覆盖视图) 展示一个覆盖全屏的模态视图。可传入多个视图配置。 ```ts fullScreenCover?: ModalPresentation | ModalPresentation[] ``` *** ## Popover(弹出菜单) 展示一个带箭头的弹出内容区域,通常用于 iPad 或大屏设备上。可设置适配策略及箭头位置。 ```ts popover?: PopoverPresentation | PopoverPresentation[] ``` ### PopoverPresentation 类型定义 ```ts type PopoverPresentation = ModalPresentation & { arrowEdge?: Edge presentationCompactAdaptation?: PresentationAdaptation | { horizontal: PresentationAdaptation vertical: PresentationAdaptation } } ``` #### 字段说明 - **`arrowEdge`**(可选):弹出箭头指向的边,默认是 `"top"`。 - **`presentationCompactAdaptation`**(可选):在紧凑环境下的展示适配策略。 ```ts type Edge = "top" | "bottom" | "leading" | "trailing" ``` *** ## ModalPresentation(通用模态视图结构) 该类型被 `sheet`、`popover` 和 `fullScreenCover` 使用,定义了基础展示结构。 ```ts type ModalPresentation = { isPresented: boolean onChanged: (isPresented: boolean) => void content: VirtualNode } ``` ### 字段说明 - **`isPresented`**:控制是否展示模态视图。 - **`onChanged`**:模态视图关闭或显示时触发的状态更新回调。 - **`content`**:展示内容的 `VirtualNode`。 *** ## PresentationAdaptation(展示适配策略) 指定在不同尺寸环境下的视图展示方式。 ```ts type PresentationAdaptation = | "automatic" | "fullScreenCover" | "none" | "popover" | "sheet" ``` - **`automatic`**:系统自动选择合适的展示方式。 - **`fullScreenCover`**:优先使用全屏覆盖。 - **`popover`**:优先使用弹出菜单形式。 - **`sheet`**:优先使用底部弹窗。 - **`none`**:尽量保持原始展示方式,不做适配。 *** ## 示例用法 ### 展示 Sheet ```tsx , message: Your changes have not been saved., }}> {/* presented content */} ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Drag Sessions, Containers and Text Clipboard.md --- # 拖放会话、容器与文本剪贴板 Scripting 提供了一套与 SwiftUI Drag & Drop 行为模型高度一致的 API,用于在脚本中实现视图间、应用内或跨应用的拖拽与放置操作。 该能力主要由以下三部分构成: - **onDrag**:将当前视图声明为拖拽源 - **onDrop**:将当前视图声明为放置目标 - **DropInfo / ItemProvider / UTType**:描述拖拽内容与状态的上下文对象 拖拽与放置是一个严格受系统控制的交互流程,部分 API 只能在特定回调中调用,文档中会明确指出这些限制。 *** ## 核心数据类型 ### DropInfo `DropInfo` 描述一次拖拽在当前放置视图上的实时状态。该对象仅在 `onDrop` 相关回调中有效。 #### 属性 ##### location: Point - 表示拖拽当前位置 - 坐标空间为 **放置视图自身的本地坐标系** - 可用于实现基于位置的高亮、插入指示线、排序逻辑等 #### 方法 ##### hasItemsConforming(types: UTType\[]): boolean - 用于判断拖拽内容中,是否至少有一个项目符合指定的 UTType - 常用于: - `validateDrop` - `dropEntered` - `dropUpdated` - 不会实际加载数据,仅用于能力判断 ##### itemProviders(types: UTType\[]): ItemProvider\[] - 返回符合指定 UTType 的 `ItemProvider` 列表 - **仅允许在 `performDrop` 回调中调用** - 在该方法返回后,系统将撤销对拖拽数据的访问权限 > 重要约束 > 必须在 `performDrop` 方法作用域内 **立即开始** 对 ItemProvider 的数据加载(如 `loadData`、`loadText`)。 > 不允许延迟到其他回调或异步逻辑中再发起加载。 *** ## DropOperation `DropOperation` 用于描述当前拖拽更新阶段,目标视图期望执行的操作类型。 可选值如下: - `"copy"` 表示复制数据(最常见,用于文件、文本、图片等) - `"move"` 表示移动数据(通常仅用于应用内部拖拽) - `"cancel"` 取消本次拖拽,不执行任何数据传输 - `"forbidden"` 明确禁止当前拖拽行为,系统通常会显示禁止指示 `DropOperation` 通常由 `dropUpdated` 回调返回,用于动态控制拖拽行为。 *** ## DragDropProps `DragDropProps` 是所有支持拖拽与放置能力的视图可选属性集合。 *** ## onDrag ### 用途 将当前视图声明为 **拖拽源**,允许用户从该视图开始一次拖拽操作。 ### 定义 ```ts onDrag?: { data: () => ItemProvider preview: VirtualNode } ``` ### 参数说明 #### data ```ts data: () => ItemProvider ``` - 返回一个 `ItemProvider` - 用于描述拖拽时传递的数据内容 - 支持文本、图片、文件、URL、自定义类型等 - 每次拖拽开始时调用 > 建议 > 仅在该回调中构造 ItemProvider,不要复用旧实例,以确保数据状态正确。 #### preview ```ts preview: VirtualNode ``` - 指定拖拽开始后显示的预览视图 - 系统会自动将其渲染为拖拽浮层 - 预览视图默认居中于源视图 *** ## onDrop ### 用途 将当前视图声明为 **放置目标**,并通过一组回调精细控制拖拽验证、状态变化与最终数据接收。 ### 定义 ```ts onDrop?: { types: UTType[] validateDrop?: (info: DropInfo) => boolean dropEntered?: (info: DropInfo) => void dropUpdated?: (info: DropInfo) => DropOperation | null dropExited?: (info: DropInfo) => void performDrop: (info: DropInfo) => boolean } ``` *** ### onDrop.types ```ts types: UTType[] ``` - 声明该视图 **允许接收的内容类型** - 如果拖拽内容不包含任意一个匹配类型: - 放置区域不会激活 - `validateDrop` 不会被调用 - 视觉高亮不会出现 *** ### validateDrop ```ts validateDrop?: (info: DropInfo) => boolean ``` - 用于判断是否允许开始一次放置操作 - 返回 `false` 将直接拒绝拖拽 - 常见用途: - 检查类型数量 - 校验业务状态(如只允许空列表接收) 默认行为:始终返回 `true` *** ### dropEntered ```ts dropEntered?: (info: DropInfo) => void ``` - 当拖拽进入放置区域时触发 - 通常用于: - 显示高亮 - 显示插入占位符 - 触发动画状态 *** ### dropUpdated ```ts dropUpdated?: (info: DropInfo) => DropOperation | null ``` - 当拖拽在放置区域内部移动时反复调用 - 用于动态返回期望的 `DropOperation` 返回值说明: - 返回具体的 `DropOperation`:更新当前拖拽行为 - 返回 `null`: - 使用上一次返回的有效值 - 若没有历史值,默认使用 `"copy"` *** ### dropExited ```ts dropExited?: (info: DropInfo) => void ``` - 当拖拽离开放置区域时触发 - 常用于清理高亮、移除占位 UI *** ### performDrop ```ts performDrop: (info: DropInfo) => boolean ``` - **最关键的回调** - 表示用户已松手,系统允许你读取拖拽数据 - 返回值: - `true`:表示成功接收并处理了拖拽 - `false`:表示放置失败 #### 重要约束(必须遵守) - 必须在该方法作用域内: - 调用 `info.itemProviders(...)` - 并立即开始数据加载 - 不允许: - 将 ItemProvider 保存到外部 - 在异步回调中延迟访问拖拽数据 这是系统级安全限制,不遵守将导致数据无法访问。 *** ## 典型使用流程总结 1. 用户从 `onDrag` 视图开始拖拽 2. 系统根据 `onDrop.types` 判断是否激活目标 3. 调用 `validateDrop` 4. 进入放置区域 → `dropEntered` 5. 移动过程中 → 多次 `dropUpdated` 6. 离开区域 → `dropExited` 7. 松手 → `performDrop` 8. 在 `performDrop` 中读取并处理数据 *** ## 设计建议与最佳实践 - 始终精确声明 `UTType`,避免过于宽泛 - 在 `dropUpdated` 中返回 `"forbidden"` 可显式阻止非法拖拽 - 复杂数据解析逻辑应在 `ItemProvider` 加载完成后的异步回调中完成,而不是在 `performDrop` 中同步阻塞 - 跨应用拖拽时,优先使用系统标准类型(text、image、file、url) *** ## iOS 27.0 拖放会话与文本剪贴板 以下接口均支持直接 props 和链式 `modifiers()`,旧系统忽略。需要返回值的回调必须同步返回,不能返回 Promise。 - `dragConfiguration: { allowMove?: boolean, allowCopyOutsideApp?: boolean }`:App 内移动默认关闭,向其他 App 复制默认允许。 - `onDragSessionUpdated(session)` / `onDropSessionUpdated(session)`:接收普通对象快照,`id` 是不透明会话标识。拖拽快照包含 phase、operation(或 null)、location、draggedItemIndex、字符串 draggedItemIDs;放下快照包含 phase、operation、location、size、itemsCount、suggestedOperations、isLocal、字符串 draggedItemIDs、reorderDestination(或 null)。来源没有提供字符串 ID 时,ID 数组为空。 - `dropConfiguration(session)`:返回 `"copy"`、`"move"`、`"cancel"` 或 `"forbidden"`,无效结果回退为 forbidden。它只选择操作,不读取或处理负载,仍需保留 drop 处理器。 - `draggable: { containerItemID: string, containerNamespace?: NamespaceID }`、`dragContainer: { payload: (itemIDs: string[]) => string[], namespace?: NamespaceID }` 和 `dragContainerSelection: { selection: string[], containerNamespace?: NamespaceID }`:支持字符串 Transferable 负载。本桥接中字符串值本身就是 ID,payload 应返回这些 ID;需要隔离容器时通过 NamespaceReader 提供命名空间。文件或自定义负载继续使用 `onDrag` / `onDrop` 与 ItemProvider。 - `copyable: string[] | (() => string[])`、`cuttable: () => string[]`、`pasteDestination: { action: (items: string[]) => void, validator?: (items: string[]) => string[] }`:文本剪贴板操作。不提供 validator 时接受全部文本;cut 回调应同步更新源数据。这些接口配置视图的 SwiftUI 命令处理,不会主动创建按钮或菜单。 27.0 SDK 中 `onCopyCommand`、`onCutCommand`、`onPasteCommand` 所在扩展仍标记 iOS unavailable,因此没有暴露这三个名称。Swift 泛型 Transferable 不能直接映射成任意 JavaScript 负载,本次新增包装明确只支持字符串。 ```tsx ids }} dragContainerSelection={{ selection: selectedIDs }} dragConfiguration={{ allowMove: true, allowCopyOutsideApp: false }} > Apple [selectedText]} pasteDestination={{ validator: items => items.filter(text => text.length > 0), action: items => insertText(items.join("\n")), }}>Clipboard target ``` ### 会话快照类型 `operation` 在 ending / ended 阶段提供操作值,其余阶段为 null;`unknown` 用于兼容未来原生阶段。非原生重排容器内的 `reorderDestination` 为 null。坐标单位为 point,快照不暴露原生会话方法或负载读取方法。 ```ts type DropOperation = 'cancel' | 'copy' | 'forbidden' | 'move' export type DragSession = { id: string phase: 'initial' | 'active' | 'ending' | 'ended' | 'dataTransferCompleted' | 'unknown' operation: DropOperation | null location: { x: number, y: number } draggedItemIndex: number draggedItemIDs: string[] } export type DropSession = { id: string phase: 'entering' | 'active' | 'exiting' | 'ended' | 'dataTransferCompleted' | 'unknown' operation: DropOperation | null location: { x: number, y: number } size: { width: number, height: number } /** Proposed native reorder destination, or null outside a reorderable container. */ reorderDestination: ReorderDestination | null itemsCount: number suggestedOperations: DropOperation[] isLocal: boolean draggedItemIDs: string[] } export type ReorderDestination = ({ position: 'before', itemID: string } | { position: 'end' }) & { collectionID?: string } export type ReorderDifference = { sources: string[] destination: ReorderDestination } ``` ### 剪切示例 同步返回文本并清空源数据。 ```tsx { const text = selectedText.value selectedText.value = "" return [text] }}>{selectedText.value} ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Gesture Input Sources.md --- # 手势输入来源 Scripting 提供了与 SwiftUI 类似的完整手势系统,可为任意视图(如 ``、``、`` 等)添加点击、长按、拖动、缩放、旋转等交互行为。 开发者既可以使用简化的 `onTapGesture` / `onLongPressGesture` / `onDragGesture` 等直接属性,也可以使用新的 `Gesture` 类接口和 `gesture` 修饰符,以获得更灵活的组合方式。 自定义键盘专用触摸区还可使用 iOS 18+ 的 [`onTouchGesture`](),接收 UIKit 的逐指开始、移动、结束和取消事件。它是独立接口,不接受 GestureMask,也不改变已有 DragGesture;速度/预测、取消及多指迁移规则请先阅读其文档。 *** ## 一、直接手势属性(简化用法) 这些属性提供最直接的交互绑定方式,适合快速使用场景。 *** ### 1. `onTapGesture` 在识别到点击手势时执行指定操作。 #### 类型 ```ts onTapGesture?: (() => void) | { count: number perform: () => void } ``` #### 参数 | 参数 | 类型 | 默认值 | 说明 | | --------- | ------------ | --- | ----------------- | | `count` | `number` | `1` | 点击次数(1 为单击,2 为双击) | | `perform` | `() => void` | — | 识别到点击后执行的操作 | #### 示例 ```tsx // 单击触发 console.log('点击了')} /> // 双击触发 console.log('双击了') }} /> ``` *** ### 2. `onLongPressGesture` 在识别到长按手势时执行操作,可监听按压状态。 #### 类型 ```ts onLongPressGesture?: (() => void) | { minDuration?: number maxDuration?: number perform: () => void onPressingChanged?: (state: boolean) => void } ``` #### 参数 | 参数 | 类型 | 默认值 | 说明 | | ------------------- | -------------------------- | ------- | -------------- | | `minDuration` | `number` | `500` | 触发长按所需最短时间(毫秒) | | `maxDuration` | `number` | `10000` | 长按的最长持续时间(毫秒) | | `perform` | `() => void` | — | 长按触发时执行的操作 | | `onPressingChanged` | `(state: boolean) => void` | — | 按下或松开时的状态回调 | #### 示例 ```tsx // 基本用法 console.log('长按触发')} /> // 自定义参数 console.log('长按成功'), onPressingChanged: isPressing => console.log(isPressing ? '正在按压' : '已松开') }} /> ``` *** ### 3. `onDragGesture` 为视图添加拖动交互,支持实时位置变化与拖动结束事件。 #### 类型 ```ts onDragGesture?: { minDistance?: number coordinateSpace?: 'local' | 'global' onChanged?: (details: DragGestureDetails) => void onEnded?: (details: DragGestureDetails) => void } ``` #### 参数 | 参数 | 类型 | 默认值 | 说明 | | ----------------- | --------------------------------------- | --------- | ------------ | | `minDistance` | `number` | `10` | 触发拖动的最小距离(点) | | `coordinateSpace` | `'local' \| 'global'` | `'local'` | 坐标系类型 | | `onChanged` | `(details: DragGestureDetails) => void` | — | 拖动过程中回调 | | `onEnded` | `(details: DragGestureDetails) => void` | — | 拖动结束时回调 | #### `DragGestureDetails` 类型 ```ts type DragGestureDetails = { time: number location: Point startLocation: Point translation: Size velocity: Size predictedEndLocation: Point predictedEndTranslation: Size } ``` | 字段 | 说明 | | ------------------------- | ------------------- | | `time` | 当前事件时间戳(毫秒) | | `location` | 当前触摸位置 `{x, y}` | | `startLocation` | 拖动起始位置 | | `translation` | 从开始拖动至当前的偏移量 | | `velocity` | 当前速度(points/second) | | `predictedEndLocation` | 预测结束位置 | | `predictedEndTranslation` | 预测总偏移量 | #### 示例 ```tsx { console.log('当前坐标:', details.location) console.log('偏移量:', details.translation) }, onEnded: details => { console.log('预测结束位置:', details.predictedEndLocation) } }} /> ``` *** ## 二、Gesture 类接口(高级用法) 若需要更复杂的组合或同时识别多个手势,可使用 `Gesture` 类与 `gesture` 修饰符。 所有手势均返回一个 `GestureInfo` 实例,通过 `.onChanged()` 与 `.onEnded()` 注册事件。 *** ### 1. GestureInfo 类 ```ts class GestureInfo { type: string options: Options onChanged(callback: (value: Value) => void): this onEnded(callback: (value: Value) => void): this } ``` | 方法 | 说明 | | ---------------------- | ------------------- | | `.onChanged(callback)` | 手势状态变化时调用(如拖动中、缩放中) | | `.onEnded(callback)` | 手势结束时调用 | #### 示例 ```tsx console.log('点击结束')) } /> ``` *** ### 2. TapGesture(点击手势) ```ts declare function TapGesture(count?: number): GestureInfo ``` | 参数 | 类型 | 默认值 | 说明 | | ------- | -------- | --- | ---- | | `count` | `number` | `1` | 点击次数 | #### 示例 ```tsx console.log('双击了')) } /> ``` *** ### 3. LongPressGesture(长按手势) ```ts declare function LongPressGesture(options?: LongPressGestureOptions): GestureInfo type LongPressGestureOptions = { minDuration?: number maxDuration?: number } ``` | 参数 | 默认值 | 说明 | | ------------- | ----- | ---------------- | | `minDuration` | 500 | 触发所需的最短时间(毫秒) | | `maxDuration` | 10000 | 手指移动前的最长持续时间(毫秒) | #### 示例 ```tsx console.log('正在长按')) .onEnded(() => console.log('长按完成')) } /> ``` *** ### 4. DragGesture(拖动手势) ```ts declare function DragGesture(options?: DragGestureOptions): GestureInfo type DragGestureOptions = { minDistance?: number coordinateSpace?: 'local' | 'global' } ``` #### 示例 ```tsx console.log('偏移', d.translation)) .onEnded(d => console.log('速度', d.velocity)) } /> ``` *** ### 5. MagnifyGesture(缩放手势) ```ts declare function MagnifyGesture(minScaleDelta?: number | null): GestureInfo type MagnifyGestureValue = { time: Date magnification: number startAnchor: Point startLocation: Point velocity: number } ``` #### 示例 ```tsx console.log('缩放倍率', v.magnification)) .onEnded(() => console.log('缩放结束')) } /> ``` *** ### 6. RotateGesture(旋转手势) ```ts declare function RotateGesture(minAngleDelta?: Angle | null): GestureInfo type RotateGestureValue = { rotation: AngleValue velocity: AngleValue startAnchor: Point time: Date } type AngleValue = { radians: number degrees: number magnitude: number animatableData: number } ``` #### 示例 ```tsx console.log('旋转角度', v.rotation.degrees)) .onEnded(() => console.log('旋转完成')) } /> ``` *** ## 三、手势修饰符(Gesture Modifiers) 以下属性可添加在任何视图上,用于控制手势识别行为。 ```ts type GesturesProps = { gesture?: GestureProps simultaneousGesture?: GestureProps highPriorityGesture?: GestureProps defersSystemGestures?: EdgeSet } ``` *** ### 1. `gesture` 为视图添加一个手势。 ```tsx console.log('点击')) } /> ``` *** ### 2. `highPriorityGesture` 使该手势的识别优先于同视图上的其他手势。 ```tsx console.log('双击优先')) } /> ``` *** ### 3. `simultaneousGesture` 允许多个手势同时识别。 ```tsx console.log('长按')) } gesture={ TapGesture() .onEnded(() => console.log('点击')) } /> ``` *** ### 4. `defersSystemGestures` 设置屏幕边缘的优先权,使自定义手势优先于系统手势(如返回手势)。 ```tsx 边缘手势优先 ``` | 值 | 说明 | | -------------- | ------------ | | `'top'` | 顶部边缘 | | `'leading'` | 左边缘(RTL 时为右) | | `'trailing'` | 右边缘 | | `'bottom'` | 底部边缘 | | `'horizontal'` | 左右两侧 | | `'vertical'` | 上下两侧 | | `'all'` | 所有边缘 | *** ## 四、GestureMask(手势优先级控制) 定义当添加多个手势时的优先策略。 ```ts type GestureMask = "all" | "gesture" | "subviews" | "none" ``` | 值 | 说明 | | ------------ | --------------- | | `"all"` | 启用所有手势(默认) | | `"gesture"` | 仅启用当前手势,禁用子视图手势 | | `"subviews"` | 启用子视图手势,禁用当前手势 | | `"none"` | 禁用所有手势 | #### 示例 ```tsx console.log('Tapped')), mask: 'gesture' }} > Tap me ``` *** ## 五、总结对比表 | 手势类型 | 描述 | 对应类函数 | 直接属性 | 常用回调 | | ---- | ------- | ------------------ | -------------------- | ----------------------------- | | 点击 | 检测单击或多击 | `TapGesture` | `onTapGesture` | `.onEnded()` | | 长按 | 检测持续按压 | `LongPressGesture` | `onLongPressGesture` | `.onChanged()` / `.onEnded()` | | 拖动 | 检测移动轨迹 | `DragGesture` | `onDragGesture` | `.onChanged()` / `.onEnded()` | | 缩放 | 双指缩放 | `MagnifyGesture` | — | `.onChanged()` / `.onEnded()` | | 旋转 | 双指旋转 | `RotateGesture` | — | `.onChanged()` / `.onEnded()` | *** ## 输入来源过滤(iOS 27.0+) `GestureInputKinds` 可以是 `"all"`,或由 `"directTouch"`、`"indirectTouch"`、`"pencil"`、`"pointer"` 组成的数组。省略表示允许全部来源,空数组表示不接受任何来源。旧系统忽略过滤参数,保留原有手势行为。 `onTapGesture`、`onLongPressGesture`、`onDragGesture` 的对象参数支持 `inputKinds`。`onTapGesture.perform` 的对象形式会收到指定坐标空间的 `{ x, y }`,函数简写仍不带参数;`count` 默认 1。 `TapGesture` 支持原有数字 count 或 `{ count?, inputKinds? }`;`DragGesture` 与 `LongPressGesture` 在原有 options 中增加 `inputKinds`;`RotateGesture(minAngleDelta?, inputKinds?)` 和 `MagnifyGesture(minScaleDelta?, inputKinds?)` 增加可选第二参数,保留旧调用方式。通过 `gesture`、`simultaneousGesture`、`highPriorityGesture` 使用手势对象时同样生效。 ```tsx console.log(point) }}>Tap {})}>Double tap Zoom ``` ### 输入来源类型 ```ts type GestureInputKind = "directTouch" | "indirectTouch" | "pencil" | "pointer" type GestureInputKinds = "all" | GestureInputKind[] ``` *** ## 设备铰链变化(iOS 27.1+) `onHingeChange` 支持 `(oldContext, newContext) => void`,或 `{ isEnabled?: boolean, action: (oldContext, newContext) => void }`。isEnabled 默认 true,false 关闭观察。支持直接 props 和链式 modifiers;旧系统忽略此修饰符。 每个 DeviceHingeContext 包含 `hinge: null | { status, angle }`。status 为 closed、partiallyOpen、fullyOpen 或 unknown;angle 包含 degrees 和 radians。hinge 为 null 表示信息不可用,也包括没有铰链的设备。回调报告变化,不保证提供初始事件。观察需要正在呈现的脚本视图,它不是后台监听 API;小组件与 Live Activity 不提供持续的 JavaScript 铰链观察。 应将其用于可选布局适配。常见任务不能依赖特定折叠角度,应保留可访问的控件,并在 hinge 为 null 时提供可用布局。避免随持续变化的角度频繁播报或移动 VoiceOver 焦点。 ```tsx { console.log(newContext.hinge?.angle.degrees ?? "unavailable") }}}> Content remains usable without hinge data. ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Native Drag Reordering.md --- # 原生拖拽重排 `ForEach` 是 Scripting 中用于渲染可变数量子视图的组件,用于构建动态列表、可编辑列表,以及支持系统级的删除与移动行为。其设计参考 SwiftUI 的 `ForEach`,并与 Scripting 的 `Observable` 状态管理系统深度集成。 组件支持两种模式: 1. **旧版模式(已不推荐使用)**:`count + itemBuilder` 2. **推荐的现代模式**:`data: Observable + builder` *** ## 1. 类型定义 ## ForEachDeprecatedProps(已不推荐) ```ts type ForEachDeprecatedProps = { count: number; itemBuilder: (index: number) => VirtualNode; onDelete?: (indices: number[]) => void; onMove?: (indices: number[], newOffset: number) => void; }; ``` ### 参数说明 #### count: number 要渲染的元素数量,`itemBuilder` 将从 0 到 `count - 1` 依次构建每个子视图。 #### itemBuilder(index) 基于索引构建一个 `VirtualNode`。 #### onDelete(indices) 注册删除行为。 当 ForEach 放置在 `List` 中时,如果提供 `onDelete`,将启用系统级的滑动删除交互。 回调触发时,`List` 中对应的行已被移除,你必须在回调中同步删除数据源中的对应项目。 #### onMove(indices, newOffset) 注册移动行为,用于支持编辑状态下的拖动排序。 如希望禁用移动能力,可传入 `null`。 *** ## 2. ForEachProps(推荐使用) ```ts type ForEachProps = | ForEachDeprecatedProps | { data: Observable; builder: (item: T, index: number) => VirtualNode; editActions?: "delete" | "move" | "all" | null; }; ``` ### 参数说明 #### data: Observable\ 一个可观察数组,数组元素必须包含唯一的 `id: string` 字段。 使用 `Observable` 的好处: - 当数组变动(增删改)时,会自动触发 SwiftUI 刷新 - 可以保留动画 - 更接近 SwiftUI 中 `ForEach($items)` 的使用体验 - 支持与 `List`、`NavigationStack` 等组件无缝联动 #### builder(item, index) 用于基于当前数组的每个元素构建对应的 VirtualNode。 **注意:必须为返回的子节点提供唯一的 key(通常使用 item.id)。** #### editActions: "delete" | "move" | "all" | null 控制 ForEach 的可编辑能力: | 值 | 含义 | | ---------- | ------------- | | `"delete"` | 仅启用删除 | | `"move"` | 仅启用移动(拖动排序) | | `"all"` | 同时启用删除与移动 | | `null` | 不提供任何编辑能力(默认) | 当 `ForEach` 位于 `List` 内部时,编辑能力会自动映射到系统提供的交互方式。 *** ## 3. ForEachComponent 接口 ```ts interface ForEachComponent { (props: ForEachProps): VirtualNode; } ``` `ForEach` 是一个泛型组件,接受带有 `id` 的任意数据类型。 *** ## 4. 系统级删除交互示例 当 `ForEach` 放在 `List` 内部,并使用 `data + builder` 模式时,系统会自动启用 swipe-to-delete,只需正确提供 `id` 和编辑能力。 ### 示例代码 ```tsx function View() { const fruits = useObservable(() => ["Apple", "Bananer", "Papaya", "Mango"].map((name, index) => ({ id: index.toString(), name, })) ); return ( , }}> {item.name}} /> ); } ``` *** ## 5. 使用建议与最佳实践 ### 1. 推荐使用 `data: Observable` 方案 新版 API 更接近 SwiftUI 行为,拥有更好的性能与类型推断支持,且未来将接入更多 SwiftUI-style 的能力。 ### 2. 每个元素必须拥有 `id: string` 这是确保 Diff 和动画正确工作的基础。 ### 3. 必须为 builder 返回的节点提供 `key={item.id}` 否则可能导致: - 动画不生效 - 列表渲染混乱 - 删除或移动行为出错 ### 4. 若需要与编辑按钮联动,必须放置于 `List` 中 并设置 toolbar: ```tsx toolbar={{ topBarTrailing: }} ``` *** ## 原生拖拽重排(iOS 27.0+) 使用 data 的 ForEach 支持 `reorderable?: boolean | { collectionID: string }`,需放在设置 `reorderContainer` 的父容器中。默认关闭;旧系统忽略原生重排。现有 ReorderableForEach 组件保留原有行为。 `reorderContainer` 参数为 `{ isEnabled?: boolean, acrossCollections?: boolean, move: (difference: ReorderDifference) => void }`,默认启用、单集合。difference 包含 `sources: string[]` 和目标 `{ position: "before", itemID: string }` 或 `{ position: "end" }`。多集合时设置 `acrossCollections: true`,每个 ForEach 提供 collectionID,目标会额外包含 `collectionID`。`DropSession.reorderDestination` 使用同样的目标格式。 在 move 中同步更新 Observable 数据:先移除 sources 中的条目,再按 sources 的顺序插到目标 ID 前或数组末尾。多集合需同时更新来源和目标集合。容器内 ID 应保持唯一。这与 editActions 独立,不会自动改动数据数组。 ```tsx { const moving = sources.map(id => items.value.find(item => item.id === id)!) const remaining = items.value.filter(item => !sources.includes(item.id)) const index = destination.position === "end" ? remaining.length : remaining.findIndex(item => item.id === destination.itemID) remaining.splice(index < 0 ? remaining.length : index, 0, ...moving) items.value = remaining }}}> {item.name}} /> ``` ### 重排回调类型 ```ts type ReorderDestination = ( | { position: "before", itemID: string } | { position: "end" } ) & { collectionID?: string } type ReorderDifference = { sources: string[] destination: ReorderDestination } ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Presentation Placement.md --- # 呈现位置 这些修饰符用于配置通过 `sheet` 呈现的视图的行为和外观,包括在不同尺寸环境下的适配方式、拖拽指示器、支持的尺寸(detents)、背景交互、滚动与调整优先级等。 > 这些修饰符应作用于 **被 sheet 弹出显示的根视图**(例如 ``、`` 或 ``)。 *** ## `presentationCompactAdaptation` 定义当设备处于 **横向或纵向紧凑尺寸类(Compact Size Class)** 时,sheet 的适配方式。 ### 类型 ```ts presentationCompactAdaptation?: PresentationAdaptation | { horizontal: PresentationAdaptation vertical: PresentationAdaptation } ``` ### `PresentationAdaptation` 可选值: - `"automatic"`:系统默认行为 - `"fullScreenCover"`:使用全屏显示 - `"sheet"`:使用普通 sheet 弹出样式 - `"popover"`:使用气泡样式(部分平台支持) - `"none"`:不进行适配(尽可能维持原样) ### 示例 ```tsx {/* 弹出内容 */} ``` *** ## `presentationDragIndicator` 控制 sheet 顶部是否显示 **拖拽指示器**(即小横条)。 ### 类型 ```ts presentationDragIndicator?: "visible" | "hidden" | "automatic" ``` ### 示例 ```tsx 可以拖动顶部指示器来改变高度 ``` *** ## `presentationDetents` 定义 sheet 支持的 **高度位置(detents)**,用户可以通过拖拽在这些高度间切换。 ### 类型 ```ts presentationDetents?: PresentationDetent[] ``` ### `PresentationDetent` 可选值: - `"medium"`:大约为屏幕高度的一半(在紧凑纵向尺寸下无效) - `"large"`:占满整个屏幕高度 - `number > 1`:表示固定的高度(单位为 pt) - `0 < number <= 1`:表示按屏幕高度的百分比(例如 `0.5` 表示 50% 高度) ### 示例 ```tsx 拖动可在不同高度之间切换 ``` *** ## `presentationBackgroundInteraction` 定义在弹出页面显示时,用户是否可以与 **底层视图交互**。 ### 类型 ```ts presentationBackgroundInteraction?: | "automatic" | "enabled" | "disabled" | { enabledUpThrough: PresentationDetent } ``` ### 示例:仅在 sheet 高度较小时允许背景交互 ```tsx 当 sheet 为中等高度时,背景可交互 ``` *** ## `presentationContentInteraction` 控制在向上滑动手势中,sheet 是优先 **调整高度** 还是 **滚动内容**。 ### 类型 ```ts presentationContentInteraction?: "automatic" | "resizes" | "scrolls" ``` ### 说明 - `"resizes"`:优先调整 detent 高度,滚动内容居后 - `"scrolls"`:立即滚动内部内容(如 ScrollView) - `"automatic"`:系统默认行为(通常优先调整 detent) ### 示例 ```tsx {/* 向上滑时会立即滚动,而不会先调整 sheet 高度 */} ``` *** ## `presentationCornerRadius` 设置 sheet 背景的 **圆角半径**。 ### 类型 ```ts presentationCornerRadius?: number ``` ### 示例 ```tsx 该 sheet 具有圆角背景 ``` *** ## 完整使用示例 ```tsx function SheetPage({ onDismiss }: { onDismiss: () => void }) { return 拖动指示器可改变 sheet 高度。 ], onPresentationChanged: isPresented => console.log(isPresented), }}>Row ``` --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Tabs Picker Style.md --- # 标签式选择器 通过该属性,你可以自定义视图层次结构中选择器(Picker)的外观和行为。 *** ## 属性声明 ```tsx pickerStyle?: PickerStyle; ``` ### 描述 `pickerStyle` 属性用于设置选择器的视觉样式,使其能够适应不同的上下文和用户体验需求。 *** ### 可接受的值 `pickerStyle` 属性接受以下字符串值: - **`automatic`**:默认选择器样式,根据选择器的上下文进行适配。 - **`inline`**:将每个选项内嵌显示在当前容器中的其他视图之间。 - **`menu`**:当用户按下按钮时,将选项作为菜单显示,或者作为嵌套菜单的一部分。 - **`navigationLink`**:通过导航链接将选项呈现为推送列表样式的选择器视图。 - **`palette`**:将选项以紧凑元素行的形式呈现。 - **`segmented`**:以分段控件的形式显示选项。 - **`wheel`**:将选项显示为可滚动的轮状视图,同时展示所选选项及其附近的一些选项。 *** ### 默认行为 如果未指定 `pickerStyle`,则根据选择器的上下文自动应用默认样式(`automatic`)。 *** ## 使用示例 以下示例展示了如何在 TypeScript 代码中应用 `pickerStyle` 属性: ### 示例 1:内嵌样式 (Inline Style) ```tsx function View() { const [value, setValue] = useState(0) return { setValue(value) console.log('选择了:', value) }} > 选项 1 选项 2 选项 3 } ``` 此示例创建了一个内嵌样式的选择器。 *** ### 示例 2:分段样式 (Segmented Style) ```tsx function View() { const [value, setValue] = useState(0) return { setValue(value) console.log('选择了:', value) }} > 选项 1 选项 2 选项 3 } ``` 此示例创建了一个以分段控件形式显示的选择器。 *** ### 示例 3:滚轮样式 (Wheel Style) ```tsx function View() { const [value, setValue] = useState(0) return { setValue(value) console.log('选择了:', value) }} > 选项 1 选项 2 选项 3 } ``` 此示例创建了一个滚轮样式的选择器。 *** ## 注意事项 - `pickerStyle` 属性直接映射到 SwiftUI 的 `pickerStyle` 修饰符。 - 确保传入的字符串值与上述预定义样式之一匹配,以避免运行时错误。 通过使用 `pickerStyle`,你可以根据不同的上下文自定义选择器的外观,从而提供流畅的用户体验。 *** ## iOS 27 标签样式 `pickerStyle="tabs"` 将选择项呈现为标签,并为 VoiceOver 提供标签语义。旧系统降级为 `segmented`。 --- url: /zh/guide/Changelog/3.2.2/New iOS 27 SwiftUI APIs/Toolbar Overflow, Minimization and Item Options.md --- # 工具栏溢出、最小化与项目选项 `toolbar` 属性用于为导航栏、底部工具栏或键盘附加区域添加自定义操作项。该机制参考了 SwiftUI 中的工具栏 API,允许开发者以声明式方式将按钮、控制组等元素精确地放置在界面的特定位置。 这套系统适用于提供主操作、上下文操作或增强文本输入时的交互体验。 *** ## 定义 ```ts toolbar?: ToolBarProps ``` ### ToolBarProps 类型定义 ```ts type ToolBarProps = { bottomBar?: VirtualNode | VirtualNode[] cancellationAction?: VirtualNode | VirtualNode[] confirmationAction?: VirtualNode | VirtualNode[] destructiveAction?: VirtualNode | VirtualNode[] keyboard?: VirtualNode | VirtualNode[] navigation?: VirtualNode | VirtualNode[] primaryAction?: VirtualNode | VirtualNode[] principal?: VirtualNode | VirtualNode[] topBarLeading?: VirtualNode | VirtualNode[] topBarTrailing?: VirtualNode | VirtualNode[] } ``` *** ## 放置位置说明 `ToolBarProps` 的每个字段都对应一个界面区域,可传入单个或多个 `VirtualNode` 元素进行展示。 - **`automatic`**(隐式):由系统自动判断最佳放置位置(未在类型中显式声明)。 - **`bottomBar`**:放置于底部工具栏。 - **`cancellationAction`**:表示“取消”操作,通常用于模态界面中。 - **`confirmationAction`**:表示“确认”操作,通常用于模态界面中。 - **`destructiveAction`**:表示破坏性操作,系统可能使用红色等强调样式。 - **`keyboard`**:当键盘弹出时显示在键盘附加区域。 - **`navigation`**:用于导航行为(如返回或关闭)。 - **`primaryAction`**:表示当前上下文中的主要操作。 - **`principal`**:放置在导航栏中间区域。 - **`topBarLeading`**:放置于导航栏的前导位置(通常是左侧)。 - **`topBarTrailing`**:放置于导航栏的尾部位置(通常是右侧)。 *** ## 示例 ```tsx {}} />, {}} /> } controlGroupStyle={"palette"} > `) await webView.present({ navigationTitle: '网页视图示例' }) webView.dispose() ``` ## 请求、导航与事件 ```ts loadRequest(request: WebViewRequest): Promise stopLoading(): Promise reloadFromOrigin(): Promise waitForLoad(options?: WebViewWaitOptions): Promise getBackForwardList(): Promise goToHistoryItem(id: string): Promise addEventListener(type: WebViewEventType, listener: (event: WebViewEvent) => void): Promise removeEventListener(type: WebViewEventType, listener: (event: WebViewEvent) => void): Promise ``` `loadRequest` 接受绝对 HTTP、HTTPS、file、about 或 data URL,以及可选的 HTTP `method`(默认 GET)、字符串字典 `headers`、`Data` 类型的 `body`、正数秒 `timeoutInterval`(默认 60)和命名 `cachePolicy`。缓存策略支持 `useProtocolCachePolicy`(默认)、`reloadIgnoringLocalCacheData`、`returnCacheDataElseLoad`、`returnCacheDataDontLoad`、`reloadRevalidatingCacheData` 和 `reloadIgnoringLocalAndRemoteCacheData`。请求头和请求体属于本次导航请求,不会覆盖所有重定向或子资源。非法参数以 `code: "invalidArgument"` 拒绝;主文档加载成功返回 `true`,失败、取消或被新导航替代返回 `false`。 `stopLoading` 停止当前导航,将相关等待结果结算为 `false`。`reloadFromOrigin` 向源站重新验证当前页面,不保证绕过所有缓存。`waitForLoad()` 保留等待首次或当前加载的原有行为,已知终态会立即返回。可选参数: | 参数 | 行为 | | --------------------------- | --------------------------------------- | | `timeout?: number` | 正数秒;省略时不设等待超时。超时以 `code: "timeout"` 拒绝。 | | `nextNavigation?: boolean` | 默认 false;true 表示等待下一次导航,即使当前导航已经结束。 | | `cancelOnTimeout?: boolean` | 默认 false;true 表示此等待超时时同时停止当前导航。 | 历史列表包含 `backList`、可为 null 的 `currentItem` 和 `forwardList`。每项提供 `id`、`url`、`initialURL` 和可为 null 的 `title`。id 仅属于本控制器,且必须仍存在于其历史中;其他实例或已过期的 id 以 `invalidArgument` 拒绝。 ### 导航决策 ```ts webView.onNavigationAction = async action => "allow" webView.onNavigationResponse = response => response.canShowMIMEType ? "allow" : "cancel" ``` `onNavigationAction` 优先于 `shouldAllowRequest`;未设置新回调时保留旧回调行为。新回调可同步或通过 Promise 返回 `"allow"`、`"cancel"` 或 `"download"`。异常、非法返回值、Promise 拒绝或 60 秒未返回均取消导航。未设置 response 回调时,允许 WebKit 可显示的 MIME 类型,取消其他响应。 当前 API 版本尚未提供下载管理。返回 `"download"` 会取消导航,并发出 `error.code: "unsupported"` 的 `loadError`,不会保存文件。`getCapabilities()` 返回 `navigationPolicies: ["allow", "cancel"]` 和 `downloadPolicy: false`。 action 信息包含可为 null 的 `navigationId`/`url`、`method`、`headers`、可为 null 的 `Data` `body`、`timeoutInterval`、`navigationType`、`sourceFrame`、可为 null 的 `targetFrame`、可为 null 的 `isMainFrame` 及 `shouldPerformDownload`。targetFrame 为空表示新窗口请求。除非系统能关联原生导航,否则 action 的 `navigationId` 为 null;生命周期及 response 事件提供已接受导航的 id。公开 iOS API 未提供可靠的用户手势标志,因此 `isUserInitiated` 为 `null`。response 信息包含 `navigationId`、`url`、`mimeType`、`expectedContentLength`、可为 null 的 `statusCode`、`headers`、`isForMainFrame` 和 `canShowMIMEType`。这些回调用于导航及 frame 决策,不会拦截所有图片、脚本等请求。 ### 事件 支持 `loadStart`、`redirect`、`commit`、`loadFinish`、`loadError`、`stateChange`、`webContentProcessTerminated`、`present`、`dismiss`。事件包含 `type`、可为 null 的 `navigationId`、`isMainFrame` 和 `state: WebViewState` 快照。`loadError` 另含 `error: {code, message}`。生命周期事件的 `isMainFrame` 为 true;子 frame 下载决策不受支持时为 false。主文档生命周期事件共享导航 id;子 frame 决策通过导航回调观察。`stateChange` 会合并同一主队列轮次内的变化,不承诺逐次发送每一个进度值。 同一函数重复注册不会重复接收;移除时传入相同函数引用。监听函数异常不影响其他监听者;销毁时清理监听。事件不会自动向 VoiceOver 宣读进度;脚本界面应提供有意义的加载状态并保持可预测的焦点。 ```ts const webView = new WebViewController() const onFinish = (event: WebViewEvent) => console.log(event.state.url) await webView.addEventListener("loadFinish", onFinish) await webView.loadRequest({ url: "https://example.com/form", method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: Data.fromString("name=Scripting")!, }) await webView.removeEventListener("loadFinish", onFinish) ``` ## 用户脚本、内容世界与异步 JavaScript ```ts addUserScript(options: WebViewUserScriptOptions): Promise removeUserScript(id: string): Promise removeAllUserScripts(): Promise callAsyncJavaScript(body: string, args?: Record, options?: WebViewJavaScriptOptions): Promise ``` 用户脚本接受 `source`、`injectionTime: "documentStart" | "documentEnd"`(默认 `documentStart`)、`forMainFrameOnly`(默认 true)和可选的 `contentWorld`。添加或移除只影响后续文档,不能撤销已经执行的副作用;移除用户脚本会保留控制器内部桥接脚本。 `contentWorld` 可为 `"page"`(默认)或 `{name: "my-world"}` 命名隔离世界。不同世界共享 DOM,但 JavaScript 全局变量相互隔离。`getCapabilities()` 提供 `contentWorlds` 和 `frameTargeting`。 `callAsyncJavaScript` 执行异步**函数体**,支持 `await` 并等待其返回的 Promise。`args` 的键作为命名参数,获取结果需使用 `return`。参数仅支持无循环的 JSON 值:null、布尔值、有限数字、字符串、数组和普通对象。函数、undefined、循环引用和原生对象以 `invalidArgument` 拒绝。语法错误、抛出异常、Promise 拒绝或 WebKit 无法继续执行的 frame 以 `javaScriptError` 拒绝。导航、内容进程终止及销毁会结算未完成执行。原有 `evaluateJavaScript` 保持函数体和 `return` 语义。 options 支持 `contentWorld` 和 `frameId`,不传 frameId 时在主 frame 执行。frame token 可从 action 的 `sourceFrame`/`targetFrame` 或消息的 `info.frame` 获取。frame 信息包含 `id`、`isMainFrame`、可为 null 的 `url` 以及 `securityOrigin: {protocol, host, port}`。token 仅属于当前控制器,在**任何新导航**(包括子 frame 导航)、进程终止或销毁时保守失效。过期或其他实例的 token 以 `invalidArgument` 拒绝,它不是持久 frame 标识;文档 commit 也会使此前签发的 token 失效;仅保留最近 256 个 token,导航后或大量消息活动后需重新获取。 ```ts const id = await webView.addUserScript({ source: "window.scriptReady = true", injectionTime: "documentStart", }) await webView.loadHTML("") const value = await webView.callAsyncJavaScript( "await Promise.resolve(); return amount * 2", {amount: 21}, {contentWorld: {name: "calculation"}}, ) await webView.removeUserScript(id) ``` ## 异步消息与移除 ```ts addScriptMessageHandler

( name: string, handler: (body: P, info?: WebViewMessageInfo) => R | Promise, options?: {contentWorld?: WebViewContentWorld; includeFrameInfo?: boolean}, ): Promise removeScriptMessageHandler(name: string, options?: {contentWorld?: WebViewContentWorld}): Promise ``` 原有消息体参数不变。设置 `includeFrameInfo: true` 后,第二参数提供 `frame` 和 `contentWorld`。相同 world 中的同名注册会替换原处理器,不同 world 的同名处理器相互独立。空名称和内部名称 `callMethodsWithReply`、`callMethodsWithoutReply`、`__exec_js_callback_swift__` 会被拒绝。 网页可等待 `window.webkit.messageHandlers[name].postMessage(body)`。处理器可返回 WebKit 可序列化值或 Promise:undefined、null、布尔值、数字(包括非有限值)、字符串、Date,以及包含这些值的数组和普通对象。没有返回值时保留原有 undefined 回复;显式 null 仍为 null。异常和 Promise 拒绝会以包含 `javaScriptError` 的消息拒绝网页 Promise,不支持或循环的回复值以 `serializationError` 拒绝。60 秒未回复以 `timeout` 拒绝;替换或移除会取消该处理器未完成的回复。导航、进程终止和销毁也会取消未决回复,迟到结果不会恢复已删除的处理器。 ```ts await webView.addScriptMessageHandler("double", async (body: number) => body * 2) const reply = await webView.callAsyncJavaScript( "return await window.webkit.messageHandlers.double.postMessage(21)", ) await webView.removeScriptMessageHandler("double") ``` ## WebKit 内容规则 ```ts addContentRuleList(options: {id: string; rules: string | Array>}): Promise removeContentRuleList(id: string): Promise removeAllContentRuleLists(): Promise ``` `rules` 接受 WebKit 内容阻止规则的 JSON 文本或规则数组。编译错误以 `invalidArgument` 拒绝,编译成功后安装到本控制器。同一 id 仅在新规则编译成功后替换旧规则。移除只操作本实例的用户规则,不影响其他实例或内部脚本。移除尚在编译的规则会以 `code: "cancelled"` 取消,并阻止迟到安装。应在加载目标内容前安装规则;移除不会自动补载当前文档已被阻止的资源。 这是 WebKit 内容阻止能力,不是任意 HTTP 请求拦截。规则格式遵循 [Apple 内容阻止规则文档](https://developer.apple.com/documentation/safariservices/creating-a-content-blocker)。 ```ts await webView.addContentRuleList({ id: "images", rules: [{trigger: {"url-filter": ".*", "resource-type": ["image"]}, action: {type: "block"}}], }) await webView.loadURL("https://example.com") await webView.removeAllContentRuleLists() ``` --- url: /zh/guide/Control Widget.md --- # 控制中心的小组件 Scripting 支持用户在控制中心或锁屏界面添加按钮(Button)或开关(Toggle)控件,并通过绑定脚本 `AppIntent` 实现自定义逻辑。控件支持状态反馈、图标动态切换、隐私显示控制等能力。 *** ## 控件标签类型定义 ### `ControlWidgetLabel` 表示控件主标签或状态标签的信息结构。 | 字段名 | 类型 | 描述 | | ------------------ | ---------- | -------------------- | | `title` | `string` | 标签的文本标题。 | | `systemImage` | `string?` | 可选的 SF Symbols 图标名称。 | | `privacySensitive` | `boolean?` | 控件在设备锁定时是否隐藏该标签内容。 | *** ## 一、按钮控件:`ControlWidgetButton` 用于添加一个点击后触发指定意图的按钮控件。 ```ts function ControlWidgetButton(props: ControlWidgetButtonProps): JSX.Element ``` ### `ControlWidgetButtonProps` | 字段名 | 类型 | 描述 | | -------------------- | ----------------------------- | ---------------------------------------------------- | | `privacySensitive` | `boolean?` | 控件是否在锁屏状态下隐藏其内容与状态。 | | `intent` | `AppIntent` | 点击按钮后触发的意图(AppIntent 实例)。 | | `label` | `ControlWidgetLabel` | 按钮主标签,显示标题与图标。 | | `activeValueLabel` | `ControlWidgetLabel \| null?` | 按钮激活(Active)状态时显示的标签。设置后需同时提供 `inactiveValueLabel`。 | | `inactiveValueLabel` | `ControlWidgetLabel \| null?` | 按钮非激活(Inactive)状态时显示的标签。设置后需同时提供 `activeValueLabel`。 | > 若提供了 `activeValueLabel` 或 `inactiveValueLabel`,建议同时提供两者,以确保状态一致性。此类状态标签的图标会覆盖 `label` 中的图标。 *** ## 二、开关控件:`ControlWidgetToggle` 用于添加一个可切换状态的开关控件,自动将布尔值通过绑定意图传入。 ```ts function ControlWidgetToggle(props: ControlWidgetToggleProps): JSX.Element ``` ### `ControlWidgetToggleProps` | 字段名 | 类型 | 描述 | | -------------------- | ----------------------------- | --------------------------------------------- | | `privacySensitive` | `boolean?` | 控件是否在锁屏状态下隐藏其内容与状态。 | | `intent` | `AppIntent` | 控件状态切换时触发的意图。泛型参数 `T` 必须包含 `value: boolean`。 | | `label` | `ControlWidgetLabel` | 控件主标签。 | | `activeValueLabel` | `ControlWidgetLabel \| null?` | 控件激活(开)状态时显示的标签。需与 `inactiveValueLabel` 搭配使用。 | | `inactiveValueLabel` | `ControlWidgetLabel \| null?` | 控件非激活(关)状态时显示的标签。需与 `activeValueLabel` 搭配使用。 | *** ## 三、ControlWidget 命名空间 ```ts namespace ControlWidget ``` ### `ControlWidget.parameter: string` 用户在控件配置界面中设置的参数值,通常用于标识目标对象,如设备 ID、门编号等。 *** ### `ControlWidget.present(element: VirtualNode): void` 设置控件的显示内容。仅允许传入 `ControlWidgetButton` 或 `ControlWidgetToggle` 元素。 #### 注意: - 若使用 `control_widget_button.tsx`,只能呈现 `ControlWidgetButton`; - 若使用 `control_widget_toggle.tsx`,只能呈现 `ControlWidgetToggle`; - 若控件需要在锁屏隐藏,可在顶层组件上设置 `privacySensitive`; - 如果仅需要隐藏标签或状态信息,可在相应的 `ControlWidgetLabel` 中设置 `privacySensitive`。 #### 示例: ```tsx /// app_intents.tsx export const ToggleDoorIntent = AppIntentManager.register({ name: "ToggleDoorIntent", protocol: AppIntentProtocol.AppIntent, perform: async ({ id, value }: { id: string; value: boolean }) => { await setDoorState(id, value) ControlWidget.reloadToggles() } }) /// control_widget_toggle.tsx async function run() { const doorId = ControlWidget.parameter || "default" const data = await fetchDoorData(doorId) ControlWidget.present( ) } run() ``` *** ### `ControlWidget.reloadButtons(): void` 重新加载所有按钮控件。用于意图执行后刷新状态显示。 *** ### `ControlWidget.reloadToggles(): void` 重新加载所有切换控件。常用于状态变更后触发 UI 更新。 *** ## 四、开发建议 1. 所有控件必须绑定一个 `AppIntent`,用于定义交互逻辑。 2. 切换(Toggle)控件的参数必须包含 `{ value: boolean }`,可使用`AppIntentProtocol.AppIntent`协议,内部会强制切换为 `SetValueIntent` 协议。 3. 若为控件提供状态标签,建议提供完整的 `activeValueLabel` 与 `inactiveValueLabel` 配对,以提升可读性。 4. 图标使用 SF Symbols 命名的系统图标。 5. 在意图执行中变更控件状态时,应调用 `ControlWidget.reloadButtons()` 或 `reloadToggles()` 以触发前端刷新。 --- url: /zh/guide/Custom Keyboard.md --- # 自定义键盘 `CustomKeyboard` 是 Scripting 提供的全局命名空间,用于开发 iOS 自定义键盘扩展。在 `keyboard.tsx` 脚本中使用该 API,可以渲染自定义键盘 UI,并访问当前输入状态、插入文本、控制光标、监听输入事件、调整高度,并在多个脚本之间导航切换。 ## 脚本生命周期 收起键盘或切换到其他键盘时,当前脚本会结束,其创建的 Rime 会话也会关闭。再次打开键盘时会重新运行配置的默认脚本。需要跨次保留的状态请持久化,每次脚本启动时创建新的 Rime 会话。在键盘内切换脚本失败时,原脚本仍会保留运行。 键盘启动时使用本地已编译的键盘脚本。请先在 Scripting 中构建脚本,再到键盘使用;弹出键盘不会等待 iCloud 源文件下载。启动失败或超时时可点击**重试**;有其他本地键盘时,也可点击**选择键盘脚本**。启动超时无法打断持续阻塞界面线程的同步 JavaScript。 ## 一、使用环境与前提 ### 环境要求 - 必须在脚本项目中创建名为 **`keyboard.tsx`** 的文件; - 所有 `CustomKeyboard` 方法 **仅可在键盘扩展环境中使用**; - 在 **App 脚本、Intent (`intent.tsx`)、小组件 (`widget.tsx`) 中无法使用此 API**; - 系统设置路径: ``` 设置 > 通用 > 键盘 > 键盘 > 添加新键盘 > 选择 Scripting ``` 添加后,进入 Scripting 键盘详情页,开启 **允许完全访问**,以启用网络请求、剪贴板访问等高级功能。 *** ## 二、展示键盘 UI ### `present(node: VirtualNode): void` 用于展示自定义键盘界面。必须在 `keyboard.tsx` 中调用一次。 ```tsx function MyKeyboard() { return 你好,世界 } CustomKeyboard.present() ``` *** ## 三、输入状态查询 | 属性名 | 类型 | 说明 | | ------------------ | ---------------- | ----------- | | `textBeforeCursor` | `string \| null` | 光标前的文本 | | `textAfterCursor` | `string \| null` | 光标后的文本 | | `selectedText` | `string \| null` | 当前选中的文本(如有) | | `allText` | `string` | 当前输入的文本 | | `hasText` | `boolean` | 输入框是否包含文本内容 | *** ## 四、输入特征(traits) ### `useTraits(): TextInputTraits` 获取当前输入框的系统特征(如键盘类型、返回键样式等)。值在 `textDidChange` 和 `selectionDidChange` 事件中自动更新。 ### `traits: TextInputTraits` 为静态快照,不会自动更新。建议在组件中使用 `useTraits()`。 常见字段包括: - `keyboardType`:如 `'default'`, `'emailAddress'`, `'numberPad'` - `returnKeyType`:如 `'done'`, `'go'`, `'search'` - `textContentType`:如 `'username'`, `'password'`, `'oneTimeCode'` - `keyboardAppearance`:`'light'`, `'dark'` 等 *** ## 五、文本操作 ### `insertText(text: string): void` 在光标处插入文本。 ### `deleteBackward(): void` 删除光标前的一个字符。 ### `moveCursor(offset: number): void` 移动光标位置。负数为向左,正数为向右。 ### `setMarkedText(text, location, length): void` 设置标记文本(用于拼音输入等组合输入)。 ### `unmarkText(): void` 取消当前标记文本。 *** ## 六、键盘行为控制 ### `dismiss(): void` 关闭键盘。 ### `nextKeyboard(): void` 切换至系统中的下一个键盘。 ### `requestHeight(height: number): void` 请求调整键盘高度(单位为 pt)。推荐范围为 **216\~360pt**,超出范围可能被系统忽略。 ### `setHasDictationKey(value: boolean): void` 设置是否显示语音输入按钮(麦克风图标)。 ### `setToolbarVisible(visible: boolean): void` 控制顶部工具栏的显示/隐藏。默认显示,适用于调试等场景。 *** ## 七、导航控制 ### `allScripts: KeyboardScriptInfo[]` 列出所有可以在自定义键盘扩展中运行的脚本。 ```ts const scripts = CustomKeyboard.allScripts ``` 每一项包含: | 属性 | 类型 | 说明 | | --------------- | -------- | ------------- | | `name` | `string` | 脚本的稳定名称 | | `localizedName` | `string` | 当前语言下的显示名 | | `icon` | `string` | 脚本的 SF Symbol | | `color` | `string` | 脚本颜色名称 | ### `switchToScript(scriptName: string, queryParameters?: Record): Promise` 关闭当前键盘脚本,并按脚本名称运行另一个键盘脚本。 可选的 `queryParameters` 会作为目标脚本的 `Script.queryParameters` 暴露。 ```ts await CustomKeyboard.switchToScript("Rime Pinyin DEMO", { source: Script.name, mode: "symbols", }) ``` ### `nextScript(queryParameters?: Record): Promise` 关闭当前键盘脚本,并运行下一个可用的键盘脚本。 可选的 `queryParameters` 会作为目标脚本的 `Script.queryParameters` 暴露。 ```ts await CustomKeyboard.nextScript({ source: Script.name, }) ``` ### `dismissToHome(): void` 关闭当前键盘脚本,返回 Scripting 键盘首页(脚本列表)。适用于用户在多个脚本之间自由切换的场景。 ```ts CustomKeyboard.dismissToHome() ``` *** ## 八、用户反馈 ### `playInputClick(): void` 播放标准键盘按键音,建议在模拟按键操作时调用,提升交互体验。 ```ts CustomKeyboard.playInputClick() ``` *** ## 九、事件监听 ### `addListener(event, callback): void` 注册事件监听器: | 事件名 | 回调参数 | 说明 | | --------------------- | ----------------------------------- | ------ | | `textWillChange` | `() => void` | 文本将要变更 | | `textDidChange` | `(traits: TextInputTraits) => void` | 文本已变更 | | `selectionWillChange` | `() => void` | 光标将变更 | | `selectionDidChange` | `(traits: TextInputTraits) => void` | 光标已变更 | ### `removeListener(event, callback): void` 移除指定监听器。 ### `removeAllListeners(event): void` 移除指定事件的所有监听器。 *** ## 十、完整示例 ```tsx function MyKeyboard() { const traits = CustomKeyboard.useTraits() const insert = async (text: string) => { CustomKeyboard.playInputClick() CustomKeyboard.insertText(text) } return ( 输入类型:{traits.keyboardType} ))} ) } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/Device Capabilities/AVCaptureSession & Camera Control/Live Photo/index.md --- # Live Photo 实况照片 Live Photo 是一张照片 + 拍照前后短短一段 `.mov`。`AVCapturePhotoOutput` 让你**按次**决定要不要拍——在 `capturePhoto` 时传 `livePhotoMovieFile`,resolve 出来同时包含静态图和 movie 文件路径。 ## 前置条件 - `isLivePhotoCaptureSupported === true`(所有有相机的 iPhone 都满足)。 - 一次性把开关打开: `photoOutput.isLivePhotoCaptureEnabled = true`。不支持的设备 setter 会静默 clamp 回 `false`,简单方法是写完再读一次确认。 - 调 `capturePhoto({ livePhotoMovieFile, ... })` 时 `isLivePhotoCaptureEnabled` 必须是 `true`,否则 promise **立即 reject** 而不是退化成普通拍照。 - **不要**同时开 `isAutoDeferredPhotoDeliveryEnabled`。deferred 开启后系统可能不产 `.mov`,resolve 出来的 `livePhotoMovieFileURL` 会缺失。 ## 接线 ```ts const camera = AVCaptureDevice.default("video")! const session = new AVCaptureSession() const photoOutput = new AVCapturePhotoOutput() session.configure(() => { session.sessionPreset = "photo" session.addInput(new AVCaptureDeviceInput(camera)) session.addOutput(photoOutput) }) // 一次性配置,跨多次 capturePhoto 都生效。 photoOutput.isLivePhotoCaptureEnabled = true await session.startRunning() const ts = Date.now() const photoFile = `${FileManager.documentsDirectory}/live_${ts}.heic` const movieFile = `${FileManager.documentsDirectory}/live_${ts}.mov` const result = await photoOutput.capturePhoto({ codec: "hevc", photoFile, // ← 后面要存进系统照片库的话, 必传 livePhotoMovieFile: movieFile, livePhotoVideoCodec: "hevc", }) console.log("photo:", result.image.width, "×", result.image.height) console.log("still file:", result.photoFileURL) console.log("movie:", result.livePhotoMovieFileURL) ``` Resolve 出的对象除了标准的 `image / metadata / isRawPhoto / isDeferredProxy`,多 `photoFileURL: string`(传了 `photoFile` 时)和 `livePhotoMovieFileURL: string`(传了 `livePhotoMovieFile` 时)。没要 Live Photo,`.mov` 字段不出现。 ### 为什么 Live Photo 必须用 `photoFile` `capturePhoto` 总会给你 `result.image: UIImage` —— 但 `UIImage` 是已经解码的位图,**没有**原始 metadata。把 Live Photo 存进系统照片库时,`Photos.saveLivePhoto(...)` 内部走 PhotoKit,PhotoKit 会校验 still 和 `.mov` 共享一个 Live Photo asset identifier(写在 still 的 Apple Maker Note key 17、`.mov` 的 `com.apple.quicktime.content.identifier`)。用 `image.toJPEGData()` 重编码出的 JPEG **没有**这个 identifier,PhotoKit 会拒绝配对并报 **`PHPhotosErrorDomain 3302`**。 `photoFile` 选项让 bridge 把 `photo.fileDataRepresentation()` 原始 bytes 直接写到磁盘,Maker Note 完整保留。把 `result.photoFileURL` 喂给 `Photos.saveLivePhoto({ imagePath, videoPath })`,配对就通了。 ## resolve 实际在等什么 Live Photo 触发两路并行 AVFoundation 回调:一路给静态图、一路给 `.mov`。bridge 等**两路都到齐**才 resolve——保证拿到完整一对,或者拿到错误。AVFoundation 不保证两者的回调顺序,所以**别用文件时间戳推断顺序**。 系统会在最后跑一个"capture finish"统一收尾。如果中途某一路出问题(比如 `.mov` 被丢),bridge 会用已到达的部分兜底 resolve,不会把 promise 吊死。 ## 路径规则 - 必须传**绝对路径**,以 `.mov` 结尾。`${FileManager.documentsDirectory}/...` 是最常用的可写位置。 - AVFoundation 拒绝向已存在的路径写。bridge 在拍照前**自动删除**目标路径的旧文件,免得你手动 cleanup。 - `.mov` 不大(1.5 秒大约 2–4 MB)。连拍场景请自己清理旧文件。 ## 编码选择 `livePhotoVideoCodec` 可选: - `"hevc"` — iPhone 7 起的设备首选,文件更小。 - `"h264"` — 兼容性更好(老系统、部分剪辑工具)。 如果传了设备不在 `availableLivePhotoVideoCodecTypes` 列表里的 codec,bridge 让 AVFoundation 自己挑默认,不会让 capture 整个失败。需要确认实际写入了什么,用 `AVAsset` 打开读 track 信息即可。 ## 注意 - Live Photo + `flashMode = "on"` 可以用,但拍下来的 `.mov` 会带闪光闪烁,设计时考虑。 - 你拿到的 `.mov` 跟 Photos.app 拍下来的一样,会有快门前后短短一段预滚 / 后滚。 - `capturePhoto` 只把文件写到磁盘,**不会**自动入系统照片库。要把图 + clip 作为关联 Live Photo 存进 Photos(像 Camera.app 那样),用 [`Photos.saveLivePhoto`](#): ```ts await Photos.saveLivePhoto({ imagePath: result.photoFileURL!, // 用 photoFile 选项写盘的原始 HEIC videoPath: result.livePhotoMovieFileURL!, // livePhotoMovieFile 选项写盘的 .mov shouldMoveFile: true, // 两个文件 move 进 Photos,而不是 copy }) ``` 这会把两份资源配对成一个 PHAsset,Photos.app 长按会有 "Live" 动画。首次调用时系统自动弹照片库权限授权。**千万不要**把 `result.photoFileURL` 换成 `result.image.toJPEGData()` 写盘的结果 —— 重编码出的 JPEG 没有 Live Photo asset identifier, PhotoKit 会拒绝配对。 ## 手上只有视频、没有相机? 如果素材是文件而不是实时拍摄——录屏、下载的片段、相册里的视频——根本不需要 capture session。`LivePhoto.createFromVideo(...)` 能从任意本地视频生成合规资源对,见《把视频变成实况照片》一页。 --- url: /zh/guide/Device Capabilities/AVCaptureSession & Camera Control/Live Photo/index_example.md --- # 示例 ```tsx import { Button, CaptureVideoPreviewView, HStack, Image, Navigation, NavigationStack, Script, Spacer, Text, Toolbar, ToolbarItem, useEffect, useMemo, useObservable, VStack } from "scripting" type Shot = { index: number image: UIImage photoSize: string /** native 写盘的原始 still bytes(HEIC/JPEG),含 Live Photo asset identifier */ photoURL?: string movieURL?: string movieSize?: number ms: number isDeferredProxy: boolean } function View() { const dismiss = Navigation.useDismiss() const isRunning = useObservable(false) const shots = useObservable([]) const captureCount = useObservable(0) const lastError = useObservable("") const livePhotoSupp = useObservable(false) const livePhotoEn = useObservable(false) const { session, camera, photoOutput } = useMemo(() => { const camera = AVCaptureDevice.default("video")! const session = new AVCaptureSession() const input = new AVCaptureDeviceInput(camera) const photoOutput = new AVCapturePhotoOutput() session.configure(() => { session.sessionPreset = "photo" if (session.canAddInput(input)) session.addInput(input) if (session.canAddOutput(photoOutput)) session.addOutput(photoOutput) }) // 必须在 addOutput 之后查 supported,在那之前 photoOutput 没绑 session 时 supported=false。 return { session, camera, photoOutput } }, []) useEffect(() => { async function start() { try { await session.startRunning() isRunning.setValue(true) // Live Photo 必须开启 enabled 之后才会真正生效。 photoOutput.isLivePhotoCaptureEnabled = true // 读回真实值: 不支持的设备 setter 会被 clamp 回 false。 livePhotoSupp.setValue(photoOutput.isLivePhotoCaptureSupported) livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) console.log("[startRunning]", { preset: session.sessionPreset, liveSupp: photoOutput.isLivePhotoCaptureSupported, liveEn: photoOutput.isLivePhotoCaptureEnabled, }) } catch (e) { await Dialog.alert({ message: `Failed to start: ${String(e)}` }) dismiss() } } start() return () => { session.stopRunning().finally(() => session.dispose()) } }, []) async function takeLivePhoto() { const idx = captureCount.value + 1 captureCount.setValue(idx) const ts = Date.now() // 同时让 native 写盘 still + .mov。两份文件共享 Apple Maker Note 里的 // Live Photo asset identifier, Photos.saveLivePhoto 才能 pair 上。 const photoFile = `${FileManager.documentsDirectory}/live_${idx}_${ts}.heic` const movieFile = `${FileManager.documentsDirectory}/live_${idx}_${ts}.mov` const start = Date.now() try { const result = await photoOutput.capturePhoto({ codec: "hevc", photoFile, livePhotoMovieFile: movieFile, livePhotoVideoCodec: "hevc", }) const ms = Date.now() - start // 读 movie 文件大小供 UI 显示 let movieSize: number | undefined if (result.livePhotoMovieFileURL) { try { const stat = await FileManager.stat(result.livePhotoMovieFileURL) movieSize = stat.size } catch { /* ignore */ } } shots.setValue([{ index: idx, image: result.image, photoSize: `${result.image.width}×${result.image.height}`, photoURL: result.photoFileURL, movieURL: result.livePhotoMovieFileURL, movieSize, ms, isDeferredProxy: result.isDeferredProxy, }, ...shots.value].slice(0, 6)) lastError.setValue("") } catch (e) { lastError.setValue(String(e)) } } /** 不开 Live Photo,验证退化路径:resolve 不应包含 livePhotoMovieFileURL */ async function takeRegular() { const idx = captureCount.value + 1 captureCount.setValue(idx) const start = Date.now() try { const result = await photoOutput.capturePhoto({ codec: "hevc" }) shots.setValue([{ index: idx, image: result.image, photoSize: `${result.image.width}×${result.image.height}`, movieURL: result.livePhotoMovieFileURL, // 应为 undefined ms: Date.now() - start, isDeferredProxy: result.isDeferredProxy, }, ...shots.value].slice(0, 6)) lastError.setValue("") } catch (e) { lastError.setValue(String(e)) } } /** * 把最新一张 Live Photo 配对存进系统照片库。 * 关键: `imagePath` 必须用 native 写盘的 `result.photoFileURL`(原始 HEIC, * 含 Apple Maker Note 里的 Live Photo asset identifier),用 toJPEGData 重编码 * 出来的 JPEG 会丢这个 identifier, Photos.saveLivePhoto 报 PHPhotosError 3302。 * `shouldMoveFile: true` 会把磁盘上两个文件 move 进 Photos,本地副本就消失了。 */ async function saveLast() { const last = shots.value[0] if (!last) { lastError.setValue("Capture a Live Photo first") return } if (!last.photoURL || !last.movieURL) { lastError.setValue("Last capture missing photoURL or movieURL (was it a Regular shot?)") return } try { await Photos.saveLivePhoto({ imagePath: last.photoURL, videoPath: last.movieURL, shouldMoveFile: true, }) lastError.setValue(`Saved Live Photo #${last.index} to Photos library`) } catch (e) { lastError.setValue(`Save failed: ${String(e)}`) console.error(e) } } /** 故意关掉 enabled 再调 Live Photo,期望 promise reject */ async function probeReject() { photoOutput.isLivePhotoCaptureEnabled = false livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) try { await photoOutput.capturePhoto({ livePhotoMovieFile: `${FileManager.documentsDirectory}/should_reject.mov`, }) lastError.setValue("Unexpected: did not reject") } catch (e) { lastError.setValue(`OK (rejected): ${String(e)}`) } finally { // 恢复 enabled 方便继续测 photoOutput.isLivePhotoCaptureEnabled = true livePhotoEn.setValue(photoOutput.isLivePhotoCaptureEnabled) } } return ( )} } } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/Device Capabilities/Health/Reading Quantity Samples.md --- # 读取数量型数据(HealthQuantitySample) Scripting 应用支持通过全局 API `Health.queryQuantitySamples()` 查询 HealthKit 中的**数量型健康数据**,例如步数、心率、体重、卡路里、距离等。 本文将介绍如何使用该 API 查询数据样本并解析结果。 *** ## 什么是 Quantity Sample? **Quantity Sample(数量型样本)** 表示某一时间点或时间段内的数值型健康数据。常见类型包括: - `stepCount`(步数) - `heartRate`(心率) - `bodyMass`(体重) - `activeEnergyBurned`(活动能量消耗) - `distanceWalkingRunning`(步行/跑步距离) 数据样本可能是: - **离散数据**(单次测量) - **累积数据**(时间段内累加值) *** ## API 简介 ```ts Health.queryQuantitySamples( quantityType: HealthQuantityType, options?: { startDate?: Date endDate?: Date limit?: number strictStartDate?: boolean strictEndDate?: boolean sortDescriptors?: Array<{ key: "startDate" | "endDate" | "count" order?: "forward" | "reverse" }> } ): Promise> ``` *** ## 参数说明 | 参数名 | 类型 | 描述 | | ----------------------------------- | --------- | --------------------------------------------- | | `quantityType` | `string` | 要查询的数据类型,如 `"stepCount"`、`"heartRate"` | | `startDate` / `endDate` | `Date` | 查询的时间范围 | | `limit` | `number` | 限制返回的最大样本数量 | | `strictStartDate` / `strictEndDate` | `boolean` | 是否严格匹配开始/结束时间 | | `sortDescriptors` | `Array` | 对结果进行排序,可按 `startDate`、`endDate` 或 `count` 排序 | *** ## 示例:读取步数数据 ```ts const results = await Health.queryQuantitySamples("stepCount", { startDate: new Date("2025-07-01T00:00:00"), endDate: new Date("2025-07-02T00:00:00"), limit: 10, sortDescriptors: [{ key: "startDate", order: "reverse" }] }) for (const sample of results) { const value = sample.quantityValue(HealthUnit.count()) console.log(`步数:${value} 时间:${sample.startDate} ~ ${sample.endDate}`) } ``` *** ## 示例:读取心率数据(单位为 bpm) ```ts const results = await Health.queryQuantitySamples("heartRate", { startDate: new Date(Date.now() - 3600 * 1000) // 最近一小时 }) for (const sample of results) { const bpm = sample.quantityValue( HealthUnit.count().divided(HealthUnit.minute()) ) console.log(`心率:${bpm} bpm 时间:${sample.startDate}`) } ``` *** ## 判断样本类型 返回的样本可能属于以下三种之一: - `HealthQuantitySample`(基础类) - `HealthCumulativeQuantitySample`:可调用 `.sumQuantity(unit)` - `HealthDiscreteQuantitySample`:可调用 `.averageQuantity(unit)`、`.maximumQuantity(unit)` 等 你可以使用 `in` 操作符判断: ```ts if ("averageQuantity" in sample) { const avg = sample.averageQuantity(HealthUnit.count()) console.log("平均值:", avg) } ``` *** ## 常见类型与推荐单位 | 数据类型 | 推荐单位 | | -------------------------- | ------------------------------------------------- | | `"stepCount"` | `HealthUnit.count()` | | `"heartRate"` | `HealthUnit.count().divided(HealthUnit.minute())` | | `"bodyMass"` | `HealthUnit.gram(HealthMetricPrefix.kilo)` | | `"activeEnergyBurned"` | `HealthUnit.kilocalorie()` | | `"distanceWalkingRunning"` | `HealthUnit.meter()` | *** ## 错误处理示例 ```ts try { const results = await Health.queryQuantitySamples("stepCount") console.log("共返回样本数量:", results.length) } catch (err) { console.error("查询失败:", err) } ``` *** ## 小结 读取数量型样本的流程如下: 1. 调用 `Health.queryQuantitySamples(类型, 查询参数)` 2. 遍历返回结果 3. 使用 `.quantityValue(unit)` 或 `.sumQuantity(unit)` 等方法获取数值 该 API 提供了对时间序列健康数据的强大访问能力,适用于统计、图表和趋势分析等应用场景。 --- url: /zh/guide/Device Capabilities/Health/Reading Workout Samples.md --- # 读取锻炼数据(HealthWorkout) Scripting 应用支持通过全局函数 `Health.queryWorkouts()` 从 HealthKit 查询**锻炼记录**。Workout 表示一次完整的身体活动,如跑步、步行、游泳、骑行、力量训练等。 每条锻炼记录包含活动类型、起止时间、持续时间、相关事件以及详细的统计信息(如心率、步数、距离、能量消耗等)。 *** ## 什么是 Workout? 每条 `HealthWorkout` 锻炼记录包含以下内容: - `startDate` / `endDate`:锻炼的起止时间 - `duration`:持续时间(单位:秒) - `workoutActivityType`:锻炼类型(枚举值,如跑步、步行、瑜伽等) - `metadata`:可选的附加信息 - `workoutEvents`:可选的事件数组(如暂停、继续、圈数等) - `allStatistics`:一个包含所有健康指标统计的字典,例如心率、距离、卡路里等 *** ## API 用法 ```ts Health.queryWorkouts( options?: { startDate?: Date endDate?: Date limit?: number strictStartDate?: boolean strictEndDate?: boolean sortDescriptors?: Array<{ key: "startDate" | "endDate" | "duration" order?: "forward" | "reverse" }> requestPermissions?: HealthQuantityType[] } ): Promise ``` *** ## 参数说明 | 参数名 | 描述 | | ----------------------------------- | ------------------------------------------- | | `startDate` / `endDate` | 用于筛选锻炼记录的时间范围(可选) | | `limit` | 最大返回条数(可选) | | `strictStartDate` / `strictEndDate` | 是否严格匹配起止时间 | | `sortDescriptors` | 按 `startDate`、`endDate` 或 `duration` 排序(可选) | | `requestPermissions` | 申请更多数据类型的权限(可选) | *** ## 示例:读取最近的锻炼记录 ```ts const workouts = await Health.queryWorkouts({ startDate: new Date("2025-07-01"), endDate: new Date("2025-07-05"), sortDescriptors: [{ key: "startDate", order: "reverse" }] }) for (const workout of workouts) { console.log("锻炼类型:", workout.workoutActivityType) console.log("开始时间:", workout.startDate) console.log("结束时间:", workout.endDate) console.log("持续时间(分钟):", workout.duration / 60) const heartRate = workout.allStatistics["heartRate"] const energy = workout.allStatistics["activeEnergyBurned"] if (heartRate) { const avgHR = heartRate.averageQuantity(HealthUnit.count().divided(HealthUnit.minute())) console.log("平均心率:", avgHR) } if (energy) { const kcal = energy.sumQuantity(HealthUnit.kilocalorie()) console.log("消耗能量(千卡):", kcal) } console.log("---") } ``` *** ## 如何读取统计指标 每条锻炼记录的 `allStatistics` 字典包含该锻炼过程中的各种指标统计,例如: ```ts const stat = workout.allStatistics["heartRate"] const avg = stat?.averageQuantity(HealthUnit.count().divided(HealthUnit.minute())) const max = stat?.maximumQuantity(HealthUnit.count().divided(HealthUnit.minute())) ``` 常见可用指标包括: - `"heartRate"`:心率 - `"activeEnergyBurned"`:活跃能量消耗 - `"distanceWalkingRunning"`:步行/跑步距离 - `"stepCount"`:步数 *** ## Workout Events(可选事件) 如果记录了事件(如暂停、继续、圈数等),可通过 `workout.workoutEvents` 获取: ```ts for (const event of workout.workoutEvents || []) { console.log("事件类型:", event.type) console.log("从:", event.dateInterval.start) console.log("到:", event.dateInterval.end) } ``` 事件类型包括:暂停(pause)、继续(resume)、圈数(lap)、分段(segment)等。 *** ## 注意事项 - 每条记录都是 `HealthWorkout` 实例 - `workoutActivityType` 是一个枚举,可转换为文本或图标 - 如果 `allStatistics` 中缺少某些指标,说明设备或应用在当时未记录该数据 - 可结合分类数据(如睡眠)或数量数据(如心率)进行完整的活动分析 *** ## 小结 读取 Workout 数据的步骤如下: 1. 调用 `Health.queryWorkouts(options)` 获取锻炼记录数组; 2. 可通过时间范围、数量限制、排序方式进行筛选; 3. 通过属性获取锻炼类型、时长等基本信息; 4. 使用 `allStatistics` 获取详细的健康指标; 5. 可选读取 `workoutEvents` 获取锻炼过程中的事件记录。 该 API 非常适用于展示锻炼历史、生成健身日报或绘制活动趋势图等场景。 --- url: /zh/guide/Device Capabilities/Health/Requesting Multiple Permissions at Once/index.md --- # 一次性请求多个权限 当脚本需要访问多种 HealthKit 数据时,你不必为每个权限单独发起请求。如果你在相近的时间触发多个需要授权的 `Health` API,应用会在一个短暂的时间窗口内收集这些待处理的授权需求,并弹出**一个**列出全部类型的 HealthKit 授权弹框。 这样体验更干净:用户看到的是一个合并后的弹框,而不是一连串分开的提示。 *** ## 工作方式 每个读写类 `Health` API(例如 `queryQuantitySamples`、`queryCategorySamples`、`queryWorkouts`、`dateOfBirth`)在执行前都会为其访问的数据申请授权。当你同时发起多个这样的调用时,这些申请会被合并: - 相近时间到达的请求会被合并进同一个授权弹框。 - 已经授权过的数据类型会被跳过,因此在没有新类型需要授权时不会弹框。 - 如果在弹框仍在屏幕上时又有新的请求到达,它们会排队,等当前弹框关闭后再依次弹出。 你无需调用任何显式的"请求权限"方法——只要调用所需的 API,授权会被自动发起。 *** ## 一次性请求多个权限 用 `Promise.all`(或 `Promise.allSettled`)同时发起这些查询: ```ts const results = await Promise.allSettled([ Health.queryQuantitySamples("stepCount", { limit: 1 }), Health.queryQuantitySamples("heartRate", { limit: 1 }), Health.queryCategorySamples("sleepAnalysis", { limit: 1 }), Health.queryWorkouts({ limit: 1 }), Health.dateOfBirth(), ]) console.log(results) ``` 这些查询访问的是不同的 HealthKit 数据类型,因此 HealthKit 会弹出一个涵盖所有仍需授权类型的弹框。 *** ## 逐个请求 如果你在发起下一个请求前先 `await` 上一个,那么每个调用都会在下一个开始之前完成自己的授权,用户可能会因此看到多个分开的弹框: ```ts await Health.queryQuantitySamples("stepCount", { limit: 1 }) await Health.queryCategorySamples("sleepAnalysis", { limit: 1 }) await Health.queryWorkouts({ limit: 1 }) ``` 当你事先就知道脚本需要哪些数据类型时,优先采用"同时发起"的方式。 *** ## 说明 - 查询前先检查 `Health.isHealthDataAvailable`;在不支持 HealthKit 的设备上它为 `false`。 - 授权弹框只会列出尚未确定状态的数据类型。如果所有类型都已授权,则不会弹框,查询会立即执行。 --- url: /zh/guide/Device Capabilities/Health/Requesting Multiple Permissions at Once/index_example.md --- # 示例 ```tsx import { Button, List, Navigation, NavigationStack, Script, Text } from "scripting" // 同时触发多个需要授权的 Health API,验证它们会合并成一次 HealthKit 授权弹框。 async function requestTogether() { if (!Health.isHealthDataAvailable) { await Dialog.alert({ message: "Health data is not available on this device." }) return } // Fire several permission-requiring queries at the same time. The app // collects the pending authorizations within a short window and shows a // single HealthKit permission sheet covering all of them. const tasks: Record> = { "Step Count": Health.queryQuantitySamples("stepCount", { limit: 1 }), "Heart Rate": Health.queryQuantitySamples("heartRate", { limit: 1 }), "Active Energy": Health.queryQuantitySamples("activeEnergyBurned", { limit: 1 }), "Sleep Analysis": Health.queryCategorySamples("sleepAnalysis", { limit: 1 }), "Workouts": Health.queryWorkouts({ limit: 1 }), "Date of Birth": Health.dateOfBirth(), } const labels = Object.keys(tasks) const results = await Promise.allSettled(Object.values(tasks)) const summary = results.map((result, index) => { const label = labels[index] if (result.status === "fulfilled") { const value = result.value const detail = Array.isArray(value) ? `${value.length} item(s)` : "ok" return `${label}: ${detail}` } return `${label}: failed (${result.reason})` }).join("\n") console.log(summary) await Dialog.alert({ title: "Permission results", message: summary }) } // 逐个 await 调用:每个请求在下一个开始前就完成授权,因此会弹出多个分开的授权弹框, // 与上面的"合并请求"形成对照。 async function requestSequentially() { if (!Health.isHealthDataAvailable) { await Dialog.alert({ message: "Health data is not available on this device." }) return } try { await Health.queryQuantitySamples("stepCount", { limit: 1 }) await Health.queryCategorySamples("sleepAnalysis", { limit: 1 }) await Health.queryWorkouts({ limit: 1 }) await Dialog.alert({ message: "Sequential requests finished." }) } catch (error) { await Dialog.alert({ title: "Failed", message: String(error) }) } } function Example() { return Calling several permission-requiring Health APIs at once merges their authorization into a single HealthKit sheet. })} {resp != null ? <> : <> } {/* 未选中的先画(细),选中的最后画压在上面(粗)。MapPolyline 目前不接收 opacity / 视图层 modifier,这里用 stroke width(3 vs 6)制造主次对比。 */} {routes.map((r, i) => { if (i === selectedIdx) return null return })} {routes[selectedIdx] != null ? : null} } // ─────────────────────────────────────────────────────────────────────── // Demo 4: calculateETA — time / distance only, no geometry download // ─────────────────────────────────────────────────────────────────────── function ETADemo() { type Mode = "automobile" | "walking" const [mode, setMode] = useState("automobile") const [eta, setEta] = useState(null) const [loading, setLoading] = useState(false) const [err, setErr] = useState(null) const calc = async () => { setLoading(true); setErr(null) try { const result = await MapDirections.calculateETA({ source: { coordinate: PEOPLES_SQUARE, name: "People's Square" }, destination: { coordinate: LUJIAZUI, name: "Lujiazui" }, transportType: mode, departureDate: new Date(), }) setEta(result) } catch (e) { setErr(String(e)) } finally { setLoading(false) } } return 4. `calculateETA` Skip the polyline download; get back travel time / distance / arrival window only. Cheaper than `calculate` when the UI just needs a headline number. setMode(v as Mode)} pickerStyle={"segmented"} > automobile walking `) await webView.present({ navigationTitle: '网页视图示例' }) webView.dispose() ``` ## 请求、导航与事件 ```ts loadRequest(request: WebViewRequest): Promise stopLoading(): Promise reloadFromOrigin(): Promise waitForLoad(options?: WebViewWaitOptions): Promise getBackForwardList(): Promise goToHistoryItem(id: string): Promise addEventListener(type: WebViewEventType, listener: (event: WebViewEvent) => void): Promise removeEventListener(type: WebViewEventType, listener: (event: WebViewEvent) => void): Promise ``` `loadRequest` 接受绝对 HTTP、HTTPS、file、about 或 data URL,以及可选的 HTTP `method`(默认 GET)、字符串字典 `headers`、`Data` 类型的 `body`、正数秒 `timeoutInterval`(默认 60)和命名 `cachePolicy`。缓存策略支持 `useProtocolCachePolicy`(默认)、`reloadIgnoringLocalCacheData`、`returnCacheDataElseLoad`、`returnCacheDataDontLoad`、`reloadRevalidatingCacheData` 和 `reloadIgnoringLocalAndRemoteCacheData`。请求头和请求体属于本次导航请求,不会覆盖所有重定向或子资源。非法参数以 `code: "invalidArgument"` 拒绝;主文档加载成功返回 `true`,失败、取消或被新导航替代返回 `false`。 `stopLoading` 停止当前导航,将相关等待结果结算为 `false`。`reloadFromOrigin` 向源站重新验证当前页面,不保证绕过所有缓存。`waitForLoad()` 保留等待首次或当前加载的原有行为,已知终态会立即返回。可选参数: | 参数 | 行为 | | --------------------------- | --------------------------------------- | | `timeout?: number` | 正数秒;省略时不设等待超时。超时以 `code: "timeout"` 拒绝。 | | `nextNavigation?: boolean` | 默认 false;true 表示等待下一次导航,即使当前导航已经结束。 | | `cancelOnTimeout?: boolean` | 默认 false;true 表示此等待超时时同时停止当前导航。 | 历史列表包含 `backList`、可为 null 的 `currentItem` 和 `forwardList`。每项提供 `id`、`url`、`initialURL` 和可为 null 的 `title`。id 仅属于本控制器,且必须仍存在于其历史中;其他实例或已过期的 id 以 `invalidArgument` 拒绝。 ### 导航决策 ```ts webView.onNavigationAction = async action => "allow" webView.onNavigationResponse = response => response.canShowMIMEType ? "allow" : "cancel" ``` `onNavigationAction` 优先于 `shouldAllowRequest`;未设置新回调时保留旧回调行为。新回调可同步或通过 Promise 返回 `"allow"`、`"cancel"` 或 `"download"`。异常、非法返回值、Promise 拒绝或 60 秒未返回均取消导航。未设置 response 回调时,允许 WebKit 可显示的 MIME 类型,取消其他响应。 当前 API 版本尚未提供下载管理。返回 `"download"` 会取消导航,并发出 `error.code: "unsupported"` 的 `loadError`,不会保存文件。`getCapabilities()` 返回 `navigationPolicies: ["allow", "cancel"]` 和 `downloadPolicy: false`。 action 信息包含可为 null 的 `navigationId`/`url`、`method`、`headers`、可为 null 的 `Data` `body`、`timeoutInterval`、`navigationType`、`sourceFrame`、可为 null 的 `targetFrame`、可为 null 的 `isMainFrame` 及 `shouldPerformDownload`。targetFrame 为空表示新窗口请求。除非系统能关联原生导航,否则 action 的 `navigationId` 为 null;生命周期及 response 事件提供已接受导航的 id。公开 iOS API 未提供可靠的用户手势标志,因此 `isUserInitiated` 为 `null`。response 信息包含 `navigationId`、`url`、`mimeType`、`expectedContentLength`、可为 null 的 `statusCode`、`headers`、`isForMainFrame` 和 `canShowMIMEType`。这些回调用于导航及 frame 决策,不会拦截所有图片、脚本等请求。 ### 事件 支持 `loadStart`、`redirect`、`commit`、`loadFinish`、`loadError`、`stateChange`、`webContentProcessTerminated`、`present`、`dismiss`。事件包含 `type`、可为 null 的 `navigationId`、`isMainFrame` 和 `state: WebViewState` 快照。`loadError` 另含 `error: {code, message}`。生命周期事件的 `isMainFrame` 为 true;子 frame 下载决策不受支持时为 false。主文档生命周期事件共享导航 id;子 frame 决策通过导航回调观察。`stateChange` 会合并同一主队列轮次内的变化,不承诺逐次发送每一个进度值。 同一函数重复注册不会重复接收;移除时传入相同函数引用。监听函数异常不影响其他监听者;销毁时清理监听。事件不会自动向 VoiceOver 宣读进度;脚本界面应提供有意义的加载状态并保持可预测的焦点。 ```ts const webView = new WebViewController() const onFinish = (event: WebViewEvent) => console.log(event.state.url) await webView.addEventListener("loadFinish", onFinish) await webView.loadRequest({ url: "https://example.com/form", method: "POST", headers: {"Content-Type": "application/x-www-form-urlencoded"}, body: Data.fromString("name=Scripting")!, }) await webView.removeEventListener("loadFinish", onFinish) ``` ## 用户脚本、内容世界与异步 JavaScript ```ts addUserScript(options: WebViewUserScriptOptions): Promise removeUserScript(id: string): Promise removeAllUserScripts(): Promise callAsyncJavaScript(body: string, args?: Record, options?: WebViewJavaScriptOptions): Promise ``` 用户脚本接受 `source`、`injectionTime: "documentStart" | "documentEnd"`(默认 `documentStart`)、`forMainFrameOnly`(默认 true)和可选的 `contentWorld`。添加或移除只影响后续文档,不能撤销已经执行的副作用;移除用户脚本会保留控制器内部桥接脚本。 `contentWorld` 可为 `"page"`(默认)或 `{name: "my-world"}` 命名隔离世界。不同世界共享 DOM,但 JavaScript 全局变量相互隔离。`getCapabilities()` 提供 `contentWorlds` 和 `frameTargeting`。 `callAsyncJavaScript` 执行异步**函数体**,支持 `await` 并等待其返回的 Promise。`args` 的键作为命名参数,获取结果需使用 `return`。参数仅支持无循环的 JSON 值:null、布尔值、有限数字、字符串、数组和普通对象。函数、undefined、循环引用和原生对象以 `invalidArgument` 拒绝。语法错误、抛出异常、Promise 拒绝或 WebKit 无法继续执行的 frame 以 `javaScriptError` 拒绝。导航、内容进程终止及销毁会结算未完成执行。原有 `evaluateJavaScript` 保持函数体和 `return` 语义。 options 支持 `contentWorld` 和 `frameId`,不传 frameId 时在主 frame 执行。frame token 可从 action 的 `sourceFrame`/`targetFrame` 或消息的 `info.frame` 获取。frame 信息包含 `id`、`isMainFrame`、可为 null 的 `url` 以及 `securityOrigin: {protocol, host, port}`。token 仅属于当前控制器,在**任何新导航**(包括子 frame 导航)、进程终止或销毁时保守失效。过期或其他实例的 token 以 `invalidArgument` 拒绝,它不是持久 frame 标识;文档 commit 也会使此前签发的 token 失效;仅保留最近 256 个 token,导航后或大量消息活动后需重新获取。 ```ts const id = await webView.addUserScript({ source: "window.scriptReady = true", injectionTime: "documentStart", }) await webView.loadHTML("") const value = await webView.callAsyncJavaScript( "await Promise.resolve(); return amount * 2", {amount: 21}, {contentWorld: {name: "calculation"}}, ) await webView.removeUserScript(id) ``` ## 异步消息与移除 ```ts addScriptMessageHandler

( name: string, handler: (body: P, info?: WebViewMessageInfo) => R | Promise, options?: {contentWorld?: WebViewContentWorld; includeFrameInfo?: boolean}, ): Promise removeScriptMessageHandler(name: string, options?: {contentWorld?: WebViewContentWorld}): Promise ``` 原有消息体参数不变。设置 `includeFrameInfo: true` 后,第二参数提供 `frame` 和 `contentWorld`。相同 world 中的同名注册会替换原处理器,不同 world 的同名处理器相互独立。空名称和内部名称 `callMethodsWithReply`、`callMethodsWithoutReply`、`__exec_js_callback_swift__` 会被拒绝。 网页可等待 `window.webkit.messageHandlers[name].postMessage(body)`。处理器可返回 WebKit 可序列化值或 Promise:undefined、null、布尔值、数字(包括非有限值)、字符串、Date,以及包含这些值的数组和普通对象。没有返回值时保留原有 undefined 回复;显式 null 仍为 null。异常和 Promise 拒绝会以包含 `javaScriptError` 的消息拒绝网页 Promise,不支持或循环的回复值以 `serializationError` 拒绝。60 秒未回复以 `timeout` 拒绝;替换或移除会取消该处理器未完成的回复。导航、进程终止和销毁也会取消未决回复,迟到结果不会恢复已删除的处理器。 ```ts await webView.addScriptMessageHandler("double", async (body: number) => body * 2) const reply = await webView.callAsyncJavaScript( "return await window.webkit.messageHandlers.double.postMessage(21)", ) await webView.removeScriptMessageHandler("double") ``` ## WebKit 内容规则 ```ts addContentRuleList(options: {id: string; rules: string | Array>}): Promise removeContentRuleList(id: string): Promise removeAllContentRuleLists(): Promise ``` `rules` 接受 WebKit 内容阻止规则的 JSON 文本或规则数组。编译错误以 `invalidArgument` 拒绝,编译成功后安装到本控制器。同一 id 仅在新规则编译成功后替换旧规则。移除只操作本实例的用户规则,不影响其他实例或内部脚本。移除尚在编译的规则会以 `code: "cancelled"` 取消,并阻止迟到安装。应在加载目标内容前安装规则;移除不会自动补载当前文档已被阻止的资源。 这是 WebKit 内容阻止能力,不是任意 HTTP 请求拦截。规则格式遵循 [Apple 内容阻止规则文档](https://developer.apple.com/documentation/safariservices/creating-a-content-blocker)。 ```ts await webView.addContentRuleList({ id: "images", rules: [{trigger: {"url-filter": ".*", "resource-type": ["image"]}, action: {type: "block"}}], }) await webView.loadURL("https://example.com") await webView.removeAllContentRuleLists() ``` --- url: /zh/guide/Home Screen UI/Default Scripts.md --- # 默认脚本 通过 **更多 → 默认脚本** 统一选择主 App 的两种脚本入口。 - **Home Screen(首页)**:选择包含 `home_screen_default_ui.tsx` 的脚本,该文件默认导出一个 JSX 函数组件,环境为 `Script.env === "home_screen"`。在设置中打开“显示 Home 标签页”。长按 Home 标签仍保留选择、重新加载和清除操作。 - **相机控制**:选择包含 `index.tsx` 的 TypeScript 脚本,在主 App 中以 `Script.env === "camera_control"` 运行,自行绘制相机页面或处理原生拍摄扩展交付的照片/视频。没有相机键也可点“打开相机脚本”测试。 选择默认脚本不会替用户修改 iPhone 的系统相机控制目标,仍需在系统相机设置中选择 Scripting。“刷新相机设置”会检查当前访问状态、将所选脚本更新给锁屏拍摄入口,并接收已完成的锁屏拍摄文件。按钮会显示进度和结束提示,错误单独显示;更新已安装的 DEMO 请参考最新示例代码。切换脚本存储位置或恢复已删除脚本后,如显示不可用,请重新选择。 用于系统相机目标的脚本应提供真实拍摄体验。系统相机入口约 3 秒内仍未具备运行中的相机和可用拍摄交互时,Scripting 会尝试打开内置相机;拍摄文件交给原脚本,无法接收时保留在“拍摄文件”中。共享会话无法安全释放或权限被拒绝时,可能无法接管。“打开相机脚本”不验证这些系统检查。同一环境也用于文件交接,仅接收文件不要求启动相机。请阅读[系统拍摄入口要求]()。 在 iOS 26+ 上,系统相机入口会优先使用已有的主 App 窗口,相机提示显示在本次拍摄所在窗口。 未选择默认相机脚本时,系统相机入口会先显示内置相机,再打开脚本选择页;选择后提示下次打开 Scripting 相机时生效,本次拍摄保留供手动处理。取消选择仍留在相机。 “相机控制”Section 中始终显示“拍摄文件”入口,右侧为尚未交给脚本的照片/视频文件数,没有时显示 0。进入后可浏览缩略图,点照片查看、点视频播放;主按钮将批次交给脚本,“更多”菜单可导出或删除。已交付批次仍可查看和管理,但不计入待处理数。 内置 **相机控制示例(Camera Control DEMO)** 同时包含这两个文件,完整 `index.tsx` 见[相机控制指南]()。下面是可直接使用的 Home 页组件: ```tsx import { Button, Script, Text, VStack, useState } from "scripting" export default function Home() { const [count, setCount] = useState(0) return Default Script Demo {`Environment: ${Script.env}`} {`Button count: ${count}`} ], onPresentationChanged: isPresented => console.log(isPresented), }}>Row ``` --- url: /zh/guide/View Modifiers/Swipe Actions/index_example.md --- # 示例 ```tsx import { Button, Circle, HStack, Label, List, Navigation, NavigationStack, Script, Text, useState, VStack } from "scripting" type Message = { from: string content: string isUnread: boolean } function MessageCell({ message }: { message: Message }) { return {message.from} {message.content} } function Example() { const [messages, setMessages] = useState(() => [ { from: "Maria Ruiz", content: "If you have a list of messages, you can add an action to toggle a message as unread on a swipe from the leading edge, and actions to delete or flag messages on a trailing edge swipe.", isUnread: true, }, { from: "Mei Chen", content: "Actions appear in the order you list them, starting from the swipe’s originating edge. In the example, the Delete action appears closest to the screen’s trailing edge", isUnread: true, }, { from: "Maria Ruiz", content: "By default, the user can perform the first action for a given swipe direction with a full swipe. The user can perform both the toggle unread and delete actions with full swipes. You can opt out of this behavior for an edge by setting the allowsFullSwipe parameter to false.", isUnread: false, }, { from: "Mei Chen", content: "When you set a role for a button using one of the values from the ButtonRole, system styles the button according to its role. In the example above, the delete action appears in red because it has the destructive role. If you want to set a different color, add the tint property to the button", isUnread: true, } ]) function toggleUnread(message: Message) { setMessages(messages.map(item => item !== message ? item : { ...message, isUnread: !item.isUnread })) } function deleteMessage(message: Message) { setMessages(messages.filter(item => item !== message)) } return {messages.map(message => toggleUnread(message)} tint={"systemBlue"} > {message.isUnread ? } async function run() { await Navigation.present({ element: }) Script.exit() } run() ``` --- url: /zh/guide/View Modifiers/Symbol Style/index.md --- # 符号样式 这些修饰符用于配置 SF Symbols(系统符号图标)的显示样式和动画效果,常用于 `` 组件。 *** ### `symbolRenderingMode` 设置符号图像的 **渲染模式**。 #### 类型 ```ts symbolRenderingMode?: SymbolRenderingMode ``` #### 可选值(SymbolRenderingMode): - `"monochrome"`:单色模式,使用当前前景色绘制 - `"hierarchical"`:层次渲染,根据不同图层设置不透明度(适合语义着色) - `"multicolor"`:使用符号内置颜色 - `"palette"`:分层渲染,可自定义每一层的颜色样式(需搭配 `foregroundStyle`) #### 示例 ```tsx ``` *** ### `foregroundStyle` 设置符号或前景元素的颜色样式。 #### 类型 ```ts foregroundStyle?: | ShapeStyle | DynamicShapeStyle | { primary: ShapeStyle | DynamicShapeStyle secondary: ShapeStyle | DynamicShapeStyle tertiary?: ShapeStyle | DynamicShapeStyle } ``` #### 说明: - 在 `"monochrome"` 模式下使用单个颜色或渐变; - 在 `"palette"` 模式下使用 `{ primary, secondary, tertiary }` 对象指定多层样式; - `tertiary` 可选,仅在符号有三层图层时有效。 *** ### `symbolVariant` 为符号添加特定的 **视觉变体**。 #### 类型 ```ts symbolVariant?: SymbolVariants ``` #### 可选值(SymbolVariants): - `"none"`:无变体,原始符号样式 - `"fill"`:填充样式 - `"circle"`:包裹在圆形轮廓中 - `"square"`:包裹在方形轮廓中 - `"rectangle"`:包裹在矩形轮廓中 - `"slash"`:斜杠样式,表示禁止/关闭等状态 #### 示例 ```tsx ``` *** ### `symbolEffect` 为符号添加 **动画效果**,支持静态应用或绑定数值以触发动画。 #### 类型 ```ts symbolEffect?: SymbolEffect ``` #### 使用方式: ##### 1. 静态符号效果(SymbolEffect 简写字符串) ```tsx ``` ##### 2. 动态绑定符号效果(每次值变化时触发动画) ```tsx ``` 每次 `isLiked` 状态变化时,图标会执行 bounce 动画。 ##### 3. 触发型符号效果(`isActive` 翻转触发,对应 SwiftUI `symbolEffect(_:options:isActive:)`) 在 SwiftUI 的 trigger 形态里,**稳态是 `isActive = false`**(符号可见)。翻转 `isActive` 时播放对应动画,方向因 effect 而异: | Effect | `isActive=false`(稳态) | `isActive=true`(effect 激活) | | ------------- | -------------------- | -------------------------- | | `appear` | 不可见 | 可见(appear 动画) | | `disappear` | 可见 | 不可见(disappear 动画) | | `scale` | 原始尺寸 | 已缩放 | | **`drawOn`** | **可见**(已 drawn) | **不可见**(draw-off 动画) | | **`drawOff`** | **不可见** | **可见**(draw-on 动画) | 注意 `drawOn` / `drawOff` 描述的是**动画风格**(笔画式绘制),不是激活后的最终态。`.drawOn` 行为类似 `.disappear`,只是动画用绘制风格;`.drawOff` 行为类似 `.appear`。 ```tsx const [hidden, setHidden] = useState(false) ``` ### 执行 AppIntent 的按钮 ```tsx