You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

技术问询:如何判断哪个Widget或Live Activity调用了AppIntent

识别调用AppIntent的Widget/Live Activity实例

针对Widget实例

  • 在AppIntent的perform()方法中,通过intentContext访问widgetConfiguration的widgetIdentifier属性,该值是当前Widget实例的唯一标识,可用于区分不同桌面Widget:
struct CustomWidgetIntent: AppIntent {
    func perform() async throws -> some IntentResult {
        guard let widgetID = intentContext?.widgetConfiguration?.widgetIdentifier else {
            return .result()
        }
        // 根据widgetID执行该实例专属逻辑,比如读取对应实例的缓存数据
        return .result()
    }
}
  • 如果Widget支持自定义配置,也可以在配置界面将实例专属的标识(比如用户设置的参数)存入配置中,在Intent里直接读取配置参数来区分实例。

针对Live Activity实例

  • 调用AppIntent的Live Activity实例可以通过intentContext的liveActivity属性获取,其id字段是该Live Activity的唯一标识:
struct CustomActivityIntent: AppIntent {
    func perform() async throws -> some IntentResult {
        guard let liveActivity = intentContext?.liveActivity else {
            return .result()
        }
        let activityID = liveActivity.id
        // 根据activityID执行该Live Activity实例的专属逻辑,比如更新对应实例的状态
        return .result()
    }
}
  • 另外,创建Live Activity时可以将实例专属数据存入其状态对象中,Intent里通过liveActivity.state读取这些数据,直接用于专属逻辑的执行。

注意事项

  • intentContext为可选值,需要先判空,避免非Widget/Live Activity入口(比如Siri、快捷指令)调用时出现空值问题。
  • 即使是无配置的静态Widget,每个添加到桌面的实例都会有唯一的widgetIdentifier,可用于区分。

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:12:33