本文介绍了即使同步UserDefaults,小部件也不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用XCode 12 beta 2(iOS 14 Sim)使用AppContainer将数据从我的应用程序传递到小部件.

I am using XCode 12 beta 2 (iOS 14 Sim) to pass data from my app to the widget using AppContainer.

我正在使用以下代码将数据(此处为String)保存到应用容器.

I am using the below code to save data (here String) to app container.

  let userDefaults = UserDefaults(suiteName: "group.abc.WidgetDemo")
        userDefaults?.setValue(status, forKey: "widget")
        userDefaults?.synchronize()

在Widget.swift文件中

And in the Widget.swift file


struct Provider: TimelineProvider {

    @AppStorage("widget", store: UserDefaults(suiteName: "group.abc.WidgetDemo"))
    var status: String = String()

    public func snapshot(with context: Context, completion: @escaping (MyEntry) -> ()) {
        let entry = MyEntry(status: status, date: Date())
        completion(entry)
    }

    public func timeline(with context: Context, completion: @escaping (Timeline<Entry>) -> ()) {

        let entryDate = Calendar.current.date(byAdding: .second, value: 10, to: Date())!
        let entry = MyEntry(status: status, date: entryDate)
        let timeline = Timeline(entries: [entry], policy: .atEnd)
        completion(timeline)

    }
}

请注意:时间轴输入是当前日期之后的10秒.

Please note: Timeline entry is 10 seconds post current date.

即使延迟10秒,我也无法在小部件中看到更新的信息.

Even after giving a 10 seconds delay, I am unable to see the updated information in the widget.

推荐答案

显然,在阅读了文档之后,我碰巧通过使用以下内容使其起作用

Apparently, after reading the documentation, I happen to make it work by using the below

       WidgetCenter.shared.reloadTimelines(ofKind: "WidgetDemo")

但是,如果有时,以上方法不起作用,我会尝试重新加载所有时间表.

But if sometimes, the above doesn't work I try to reload all the timelines.

       WidgetCenter.shared.reloadAllTimelines()

请注意:重新加载时间轴代码写在我们传输数据的源文件中.

Please note: the reload Timelines code is written in the source file from where we are transmitting the data.

这篇关于即使同步UserDefaults,小部件也不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:15