Widgets: An Introduction
Jyothish Johnson

Jyothish Johnson @jyothishjohnson

About: iOS developer

Location:
Kochi
Joined:
Jul 11, 2019

Widgets: An Introduction

Publish Date: Apr 24
0 0

There are times when you would want to show the apps contents/data in an helpful way upfront to the user, even when the user is not actively using your app. Widgets(iOS 14+) and Live Activities(iOS 16.1+) are the possible ways to do this.

For this article, lets start with adding a basic widget to our app.


First thing first, let's add the Widget Extension to the app.

  1. File → New → Target → Widget Extension
  2. Give a name to the extension → Finish

File → New → Target → Widget Extension

Now you will be able to see files related to a basic Widget added to your project. This template widget shows time. You should be able to see this in a struct that conforms to Widget protocol. This Widget implementation’s body needs a type of WidgetConfiguration.


There are mainly three types of WidgetConfiguration :

  • StaticConfiguration

    Used in static widgets, the data cannot be customized by the user.

  • AppIntentConfiguration

    User can configure the data populated inside this widget. Ex: Widget to track a events from a particular calendar account when user has multiple calendar accounts.

  • ActivityConfiguration

    This is exclusively used for Live Activities.

To use multiple widget types in the app use WidgetBundle protocol.


Providing Timelines for the data

Both StaticConfiguration and AppIntentConfiguration, need a timeline provider. For this we need an implementation that conforms to TimelineProvider. There are few mandatory functions that we need to implement in order to conform to above protocol.

  • func placeholder(in: Self.Context) -> Self.Entry → Used to provide a placeHolder widget view, which might be used when the user sees the widget for the first time. Think of it as a generic view to give an idea to the user about your widget.
  • func getSnapshot(in: Self.Context, completion: (Self.Entry) -> Void) → This function can be used to get a quick info about the widget in temporary states. (ie: In Widget gallery - context.isPreview = true)
  • func getTimeline(in: Self.Context, completion: (Timeline<Self.Entry>) -> Void) → This is where we can provide the information to the app, regarding when to update the widget information. We can pass a series of future dates for this. We can also specify a policy regarding when the timeline should be refreshed.
  • TimelineEntry → The data that the widget shows needs to confirm to this protocol.

Conclusion

This was a basic introduction to adding the Widget capability to your app. Further we will explore more complex implementations.

Comments 0 total

    Add comment