Search code examples
ioswidgetreloadtimelineuserdefaults

ios 14 widget: How to reload timeline after UserDefaults changed


I have a ios 14 widget that refresh every 5 minutes

let timeline = Timeline(entries: entries, policy: .atEnd)

The entries depends on the configuration on my MainApp.

I use UserDefaults to share data between MainApp and Widget.

@AppStorage("FollowingCatalog", store: UserDefaults(suiteName: "group.vn.f19.com"))
var catalogItemsData: Data = Data()

I've successfully mirrored the widget content base on UserDefaults data. BUT my problem is the my widget refresh the UI only after .atEnd policy, every 5 minutes

That cause a bad UX

How can I refresh widget content immediately right after my configuration in UserDefaults was changed?

Thanks for your supports.


Solution

  • In Keeping a Widget Up to Date by Apple, to inform your widgets to update its timeline and its content, you call:

    WidgetCenter.shared.reloadAllTimelines()
    

    This reloads all widgets that your app has. If you want to reload a specific widget (in the case your app has multiple different widget types), use WidgetCenter.shared.reloadTimelines(ofKind: "com.myApp.myWidget") instead.