Getting Started With Widgets

In this tutorial, you’ll add a widget to a large SwiftUI app, reusing its views to show entries from the app’s repository. By Audrey Tam.

3.2 (38) · 4 Reviews

Download materials
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Reconfiguring Your Widget

In EmitronWidget.swift, reconfigure your widget to IntentConfiguration.

Change the Provider protocol to IntentTimelineProvider.

struct Provider: IntentTimelineProvider {

Change the definition of getSnapshot(in:completion:) to:

public func getSnapshot(
  for configuration: TimelineIntervalIntent, 
  in context: Context, 
  completion: @escaping (WidgetContent) -> Void
) {

Now, change the definition of getTimeline(in:completion:) to:

public func getTimeline(
  for configuration: TimelineIntervalIntent, 
  in context: Context, 
  completion: @escaping (Timeline<WidgetContent>) -> Void
) {

In getTimeline(for:in:completion), change interval to use the configuration parameter:

let interval = configuration.interval as! Int

And finally, in struct EmitronWidget, change StaticConfiguration(kind:provider:) to this:

IntentConfiguration(
  kind: kind, 
  intent: TimelineIntervalIntent.self, 
  provider: Provider()
) { entry in

Build and run on your device, sign in and let the list load. Close the app, add your widget, then long-press the widget. It flips over to show an Edit Widget button.

Edit widget button

Edit widget button

Edit widget button

Tap this button to change the interval value

Change the interval value.

Change the interval value.

Change the interval value.

Setting a new interval

setting a new interval

Setting a new interval

Where To Go From Here?

Download the final project using the Download Materials button at the top or bottom of the tutorial.

This tutorial showed you how to leverage code from a large app to create a widget that displays items from the app's own repository. Here are a few ideas for you to add to your Emitron widget:

  • Design a view for the large size widget that displays two or more entries. Look at Apple's EmojiRangers sample app to see how to modify EntryView for widget families.
  • Add a widgetURL to EntryView so tapping the widget opens Emitron in that item's detail view.
  • Add intents to let users set the app's filters from the widget.

I hope you enjoyed this tutorial! Building widgets is fun!

If you have any comments or questions, feel free to join in the forum discussion below!