SwiftUI. Add specific action in Widget

Artem Mihelson
1 min readMar 31, 2022

Hi all! Check out another short how-to on SwiftUI.

This time I want to let you know how to add a specific action on your Widget.

Recently I have been working on the app that has a list on a widget. Each item in the list should be tappable and perform a specific action on item tap.

There are two types of actions you can add to your widget:

  1. General action for the entire widget. This can be achieved by adding the following modifier:
.widgetURL(<Foundation.URL?>)

In this case if you tap on a widget, your app will receive an URL you pass to the .widgetUrl() modifier.

  1. Action on specific views. This can be achieved by wrapping any View in Link:
Link(destination: URL.init(string: "com.foo/bar")!) {
Image(systemName: "doc.on.clipboard.fill")
.foregroundColor(.primary)
.padding(4)
}

In this case if you tap on Image(systemName: "doc.on.clipboard.fill")app will be opened by the URL passed to the Link which wrapped that Image

In order to retrieve the info you passed via URL, you need to use .onOpenURL function:

.onOpenURL { url in
// Parse your url here to get the passed info
}

That’s it. Happy coding!

--

--

Artem Mihelson

Founder of Pills.Kit, Proximodoro and WidgetLingo apps