Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform a deeplink from SwiftUI widget on tap

I have a simple widget (medium-sized) with two texts, and what I want is to be able to perform a deep link to lead the user to a specific section of my app, but I can't seem to find a way to do so.

The view I have written (which is very simple):

HStack {
    Text("FIRST ITEM")    
    Spacer()
    Text("SECOND ITEM")
}

I have already tried to replace

Text("SECOND ITEM")

with

Link("SECOND ITEM destination: URL(string: myDeeplinkUrl)!)

but it doesn't work either.

like image 574
Another Dude Avatar asked Oct 06 '20 16:10

Another Dude


1 Answers

  1. In the Widget view you need to create a Link and set its destination url:
struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

    var body: some View {
        Link(destination: URL(string: "widget://link1")!) {
            Text("Link 1")
        }
    }
}

Note that Link works in medium and large Widgets only. If you use a small Widget you need to use:

.widgetURL(URL(string: "widget://link0")!)
  1. In your App view receive the url using onOpenURL:
@main
struct WidgetTestApp: App {
    var body: some Scene {
        WindowGroup {
            Text("Test")
                .onOpenURL { url in
                    print("Received deep link: \(url)")
                }
        }
    }
}

It is also possible to receive deep links in the SceneDelegate by overriding:

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>)

You can find more explanation on how to use this function in this thread:

  • Detect app launch from WidgetKit widget extension

Here is a GitHub repository with different Widget examples including the DeepLink Widget.

like image 200
pawello2222 Avatar answered Oct 25 '22 10:10

pawello2222