Share Data Between Main App and Widget in Swiftui For iOS 14

Communication between iOS app & Widgets for iOS 14

Yes this is possible using one of the WidgetCenter APIs to reload your timeline.

...
// make API call
// store data in shared storage that the Widget uses


WidgetCenter.shared.reloadAllTimelines()
// OR
WidgetCenter.shared.reloadTimelines(ofKind: "WidgetKind")

Note that it's most likely preferred to use reloadTimelines(ofKind: "WidgetKind") since it will only reload the timelines of a specific widget. "WidgetKind" can be found in your WidgetConfiguration definition

Can iOS14 widget requests main app to update its data?

There's no way for a Widget to tell its parent App to refresh its data.

You can either:

  • fetch data directly in the Widget - see: How to refresh Widget data?
  • enable background notifications in the App (see How to run code when your app is terminated) and, when received one, force the Widget to refresh its timeline using:
WidgetCenter.shared.reloadAllTimelines()

In reality it's probably better to just fetch data directly in the Widget. This way you can fetch only the necessary data - Widget views usually display a lot less information than App views.

Sharing Data with AppGroup

  1. Save data to UserDefaults in your main App:
UserDefaults(suiteName: <your_app_group>)!.set("test", forKey: "test")

  1. Read data from UserDefaults in your Widget:
let testStr = UserDefaults(suiteName: <your_app_group>)!.string(forKey: "test")

If you want to save other types see:

  • How can I use UserDefaults in Swift?


Related Topics



Leave a reply



Submit