Getting started with iOS Widgets — Part II

Ayush Khare
Healint-Engineering&data
3 min readNov 16, 2021

Note: This is the second part of a 2-part tutorial. Check out the first part here.

What are we trying to achieve?

As we already have the basic structure of the widget with us, let us try to put some business logic around it. The widget is going to have 2 states depending on whether the user is currently having a migraine or is migraine free. The 2 states are shown below

Updating the SimpleEntry model

In order to get the bool value, we have to include the required files in the Widget Extension target. We can do that by Opening the files > Open code inspector > Check the widget extension target

After adding the appropriate files to MigraineBuddyWidgetExtension, let’s try to add the business logic into our Widget view to display the correct state.

In the above example, we keep a default “false” value for “isHavingMigraine” for placeholder & getSnapshot methods.

Now build and run the project and you will see the correct state depending on the logic we just included. But if I tap on “Add notes” button right now, it will just open the app, but what we are trying to achieve is to open the notes for the current running migraine so that user can directly input his entries without having to go through multiple navigations.

But how do we do that? That’s what we are going to learn next with Universal Links!

Handling Universal Links

There are two ways to open the app from a widget. If your widget is medium or large-sized, you can use Link in a portion of your view. It works similarly to Button where the action is specialised to open a web link. In our case, we will make simple and use the modifier widgetURL(url: URL) that use which we will add to our Widget Button

Let’s add the widgetUrl modifier like below

Next, we have to handle this link in our AppDelegate

Learning and building a widget is an easy to do. The main idea behind us getting this widget component out to the user is a way of replacing the app shortcuts which are not very popular among the users now.

Widgets can provide an interactive UI for your user as compared to what we currently have in the form of shortcuts.

Final thoughts

WidgetKit is one of the hot topics. By making more visible on the home screen, Widget will be more useful than before of the old Today Widget. One important thing to note is when you will create a widget, don’t bring too much information and interaction. Keep it simple for your user.

Happy Coding :)

--

--