8

How to Create Widgets With SwiftUI? An iOS App Development Guide

 2 years ago
source link: https://dzone.com/articles/how-to-create-widgets-with-swiftui-an-ios-app-deve
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Apple introduced Widgets with the launch of iOS 14 at WWDC20. The developers can create customized widgets using the newly introduced WidgetKit, which is fully built with SwiftUI. This means, to incorporate the Widgets with your app, your app should be compatible with iOS 14 and you should have basic knowledge of SwiftUI to build it.

Prerequisite

  1. XCode 12 or later
  2. iOS 14 or later
  3. Basic knowledge of SwiftUI

How To Create a Widget Extension in Your App?

1. Open your project in XCode

2. To create a new Widget, we are supposed to Add New Target in the workspace

XCode workspace

You can Add New Target to the project by pressing the ‘+’ button as displayed in the above image. Once you press the ‘+’ button, It will display a dialogue with multiple options.

Select ‘iOS’ as a platform, and select ‘Widget Extension’ from the ‘Application Extension’ category, and press Next.

Application extension category

Here, you can add the appropriate name of your choice as Product Name. We’re keeping it as ‘DemoWidget’ for demo purposes.

Configurations

There are two types of configurations: StaticConfiguration and IntentConfiguration. For the demo purpose, we are keeping StaticConfiguration for this Widget. So, please uncheck the checkbox as shown in the above image and press Finish.

And It’s done – you have successfully created a new Widget Extension. Please check the image below to see the changes.

Successful Widget Extension creation

XCode has added a new Target named DemoWidgetExtension in the TARGETS list, also one group has been added in the project name DemoWidget. Now, run the project keeping the DemoWidgetExtension target selected.

The result will be similar to the below image. Also, you can check multiple options by long-pressing the widget. Please follow the given steps

DemoWidgetExtension

So we just completed widget creation. Now, let’s understand the code and modify it as per our needs.

How To Modify Widgets as per Requirement?

Please open the DemoWidget.swift file from the DemoWidget group from the left side of the XCode window. You will see some boilerplate code already added to that file. So, this is designed to make your work easy. So let’s understand it one by one.

There are a total of 5 structs inside the DemoWidget.swift file.

Provider: It is a struct conforming to protocol TimelineProvider. It is designed to decide the rendering timeline of the widget.

It contains 3 functions:

  • func placeholder(in context: Self.Context) -> Self.Entry

It is used to pass placeholder data until the user opens the companion app and it loads the actual data in the widget.

  • func getSnapshot(in context: Self.Context, completion: @escaping (Self.Entry) -> Void)

It is used to generate the preview snapshot of the widget in the widget gallery.

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

It expects a Timeline object and it is used to decide the timeline of the widget to reload it. There are multiple TimelineReloadPolicy available to use for the Timeline of the widget. Those are atEnd, never, after(_ date: Date).

SimpleEntry: It conforms to TimelineEntry. There is a required property date. Users can define other properties based on their requirements.

DemoWidgetEntryView: It is the View that will be displayed inside Widget.

DemoWidget: It conforms to Widget and it is mainly responsible for the Widget Extension. It has two properties, kind and body, body accepts WidgetConfiguration including configurationDisplayName and description.

DemoWidget_Previews: It conforms to PreviewProvider and is responsible for previewing Widget.

Now let’s modify the boilerplate code and try to load some English words with a meaning that automatically displays a new word every 5 seconds. First of all, let’s change the SimpleEntry struct as shown below:

Changing the SimpleEntry struct

We have added two new properties word and meaning to store values of word and meaning in each entry. Now, let’s move to Provider struct and update it same as below:

Struct-provider-TimlineProvider-1024x681.png

You can see, we have added some dummy entries in placeholder and getSnapshot(…). Let’s check getTimeline(…) for the actual changes.

I’ve added an array of words with meaning, later on, you can connect it with any other sources such as UserDefaults, JSON objects, Network API calls, or anything else.

I have prepared an entries array with multiple Entry objects that have a 5 seconds Timeline and added an offset to all of them so it will be displayed for 5 seconds one after the other.

So, the logical part is done. We have transported data to Widget. But to display the data we need to modify DemoWidgetEntryView. Please update it as shown below:

Modifying DemoWidgetEntryView

Now run the project again, keep the DemoWidgetExtension as a selected target.

Displaying widget in multiple sizes

So, this is how it will display a widget in multiple sizes. Users can choose from any of them. This widget will update the word every 5 seconds. You can even fetch the data from any other sources or even configure the duration of transition of words by making the widget Configurable.

Wrapping Up

So, this is how you create widgets using Swift UI. Instead of going through the hard steps of development, you could simplify your process by approaching it professionally.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK