App Intents — 计时器示例
This article is extracted from the chat log with AI. Please identify it with caution.

我们现在继续为你已有的 计时器项目 添加 App Intent + 灵动岛联动功能。目标是:

用户通过 Siri / 快捷指令 / 小组件按钮触发 AppIntent,启动计时器,并自动在 动态岛(Dynamic Island) 显示 Live Activity。


✅ 最终效果 #

  • 用户说:“开始 25 分钟计时器”

  • App 被唤醒,启动 Live Activity

  • 锁屏和灵动岛中显示倒计时界面

  • 可选:在 Widget 上点击按钮也能触发


🧱 项目结构(回顾) #

我们已完成的结构如下:

  • TimerAttributes.swift → Live Activity 属性

  • ContentView.swift → 按钮控制启动、更新、结束

  • TimerLiveActivityWidget.swift → Widget Extension

  • ❗现在新增:

    • StartTimerIntent.swift → AppIntent

    • TimerShortcuts.swift → AppShortcutsProvider


🧩 步骤一:添加 AppIntent #

新建文件:StartTimerIntent.swift

import AppIntents
import ActivityKit

struct StartTimerIntent: AppIntent {
    static var title: LocalizedStringResource = "Start Timer"
    static var description = IntentDescription("Start a focus timer and show it in the Dynamic Island.")

    @Parameter(title: "Minutes", default: 25)
    var minutes: Int

    func perform() async throws -> some IntentResult {
        let duration = TimeInterval(minutes * 60)
        let attributes = TimerAttributes(taskName: "专注 \(minutes) 分钟")
        let contentState = TimerAttributes.ContentState(remainingTime: duration)

        do {
            _ = try Activity<TimerAttributes>.request(attributes: attributes, contentState: contentState)
            return .result(dialog: "已启动 \(minutes) 分钟计时器")
        } catch {
            return .result(dialog: "启动失败,请稍后重试")
        }
    }
}

你现在可以通过 快捷指令Siri 来启动 Live Activity 了。


🧭 步骤二:添加快捷入口(App Shortcuts) #

新建文件:TimerShortcuts.swift

import AppIntents

struct TimerShortcuts: AppShortcutsProvider {
    static var appShortcuts: [AppShortcut] {
        [
            AppShortcut(
                intent: StartTimerIntent(minutes: 25),
                phrases: [
                    "Start a timer for \(.parameter(\.minutes)) minutes",
                    "Focus for \(.parameter(\.minutes)) minutes"
                ],
                shortTitle: "Start 25m Timer",
                systemImageName: "timer"
            )
        ]
    }
}

📌 效果:Spotlight 搜索“Timer”会出现你预设的 25 分钟快捷方式。


🧪 步骤三:测试 #

你可以在以下位置测试:

  • Siri 语音:说 “开始 25 分钟计时器”

  • 快捷指令 App:搜索“Start Timer”,点击运行

  • 聚焦搜索:下拉主屏输入 Timer,点击推荐动作

✨ 此时你将看到 Live Activity 自动显示在锁屏和灵动岛。


💡 可选扩展 #

支持 Widget 按钮触发 #

如果你使用 iOS 17+ 的交互式 Widget,可以这样写:

Button(intent: StartTimerIntent(minutes: 15)) {
    Label("15 分钟", systemImage: "clock")
}

WidgetConfiguration 里直接使用 AppIntent,无需手动管理 Live Activity 状态。


✅ 最终项目文件结构如下: #

TimerLiveActivityApp/
├── TimerAttributes.swift
├── ContentView.swift
├── StartTimerIntent.swift       ← 新增
├── TimerShortcuts.swift         ← 新增
└── TimerLiveActivityExtension/
    └── TimerLiveActivityWidget.swift

🧩 你还可以继续做的事: #

  • 使用 Timer 自动更新 remainingTime 并刷新 Live Activity(模拟倒计时)

  • 添加一个“结束计时器”的 AppIntent

  • AppEntity 管理多个计时器(例如任务列表)

本文共 834 字,创建于 May 19, 2025
相关标签: Xcode, SwiftUI, ByAI, ChatGPT