Perform a deeplink from SwiftUI widget on tap

心已入冬 提交于 2020-12-26 07:23:24

问题


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.


回答1:


  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.




回答2:


Also, you can do it using AppDelegate (if you not using SceneDelegate):

.widgetURL(URL(string: "urlsceheme://foobarmessage"))

// OR

Link(destination: URL(string: "urlsceheme://foobarmessage")!) {
    Text("Foo")
}

Set this code within AppDelegate

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
   let message = url.host?.removingPercentEncoding // foobarmessage
   return true
}


来源:https://stackoverflow.com/questions/64230355/perform-a-deeplink-from-swiftui-widget-on-tap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!