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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With