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
相关产品推荐
相关产品推荐

