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

Swift:如何从WidgetCenter获取的WidgetInfo中获取WidgetLocation?

获取WidgetLocation的方法说明

目前通过WidgetCenter.getCurrentConfigurations(_:)返回的WidgetInfo确实没有直接暴露WidgetLocation相关的公开属性,官方文档里也没有相关说明。不过可以通过以下间接方式获取:

  • 利用App Group共享数据:在Widget的getTimeline(for:context:completion:)方法中,context参数包含widgetLocation属性,你可以将这个位置信息存储到App Group的共享容器中,之后主App从该容器读取对应Widget的位置数据。示例代码如下:

    // Widget Extension 中
    func getTimeline(for configuration: StaticConfiguration, context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
        let location = context.widgetLocation
        // 存储到App Group
        if let sharedDefaults = UserDefaults(suiteName: "group.your.app") {
            sharedDefaults.set(location.rawValue, forKey: "WidgetLocation_\(configuration.widgetKind)")
        }
        // 后续Timeline逻辑处理...
    }
    
    // 主App中
    WidgetCenter.shared.getCurrentConfigurations { result in
        switch result {
        case .success(let widgetInfos):
            for info in widgetInfos {
                if let sharedDefaults = UserDefaults(suiteName: "group.your.app") {
                    if let locationRaw = sharedDefaults.string(forKey: "WidgetLocation_\(info.kind)"),
                       let location = WidgetLocation(rawValue: locationRaw) {
                        // 成功获取对应Widget的位置
                        print("Widget \(info.kind) 的位置: \(location)")
                    }
                }
            }
        case .failure(let error):
            print("获取Widget配置失败: \(error)")
        }
    }
    
  • 注意事项:这种方式依赖Widget的刷新时机,只有当Widget触发刷新时,位置信息才会被更新。如果用户调整了Widget位置但Widget还未刷新,主App获取到的可能是旧数据。

关于你提到的widgetFamily存在但无location字段的疑问,苹果可能出于隐私或API设计考量,没有将WidgetLocation直接开放在WidgetInfo中,目前只能通过上述间接方式获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:49:55