Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Widget not getting updated even when UserDefaults are synchronized

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.

like image 722
Abhishek Bedi Avatar asked Jul 13 '20 09:07

Abhishek Bedi


Video Answer


1 Answers

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.

like image 59
Abhishek Bedi Avatar answered Oct 11 '22 15:10

Abhishek Bedi