iOS WidgetKit - Widget Not Getting updated even when UserDefaults are synchronized

被刻印的时光 ゝ 提交于 2020-08-10 01:13:54

问题


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

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()

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)

    }
}

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

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


回答1:


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

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

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

       WidgetCenter.shared.reloadAllTimelines()

Hope Apple comes with a fix soon.

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



来源:https://stackoverflow.com/questions/62873336/ios-widgetkit-widget-not-getting-updated-even-when-userdefaults-are-synchroniz

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!