jackson89
jackson89

Reputation: 203

Communication between iOS app & Widgets for iOS 14

I'm currently creating my first widgets for my applications. The data is obtained via an API call. I would like to know if it is possible to make this request from the application and then send the result of this request to the widget ? (a bit like WatchConnectivity does for the watch)

Thanks for your help :-)

Upvotes: 7

Views: 4628

Answers (2)

Artem Kirillov
Artem Kirillov

Reputation: 1398

Generally widgets are not supposed to receive any data directly from the app. Widgets have got a concept of TimelineProvider which generates a timeline consisting of timeline entries. Each entry specifies the date and time to update the widget’s content and the content itself. If content needs to be fetched from the server, you can use standard URLSession API in the methods of your timeline provider, and attach the data to your timeline entry. That’s why timeline provider has got completion handler as parameter in its method:

func getTimeline(in: Self.Context, completion: (Timeline<Self.Entry>) -> Void)

WidgerCenter API (recloadAllTimelines() or reloadTimelines(ofKind:)) is supposed to be used to inform WidgetKit when a time line changes. For example, when user changes something in the main app, sends request to the backend, updates data base with new info, you need to initiate widget update as well to fetch updated data and refresh.

Upvotes: 3

Taylor Johnson
Taylor Johnson

Reputation: 1953

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

Upvotes: 3

Related Questions