SwiftUI 中的 widgetURL

Sai*_*esh 5 widget ios widgetkit swiftui

我们到底需要在里面指定什么 URL .widgetURL()

在 WWDC 会议上关于 Widget Code Below 的会议中,他们使用了.widgetURL(entry.character.url). 这里的entry.character.url是URL(string: "game:///egghead")!

请解释一下我们需要通过这里(widgetURL())的 URL 才能到达 APP 的特定视图?

ngb*_*ngb 6

url 的格式为 schema://someAction

冒着过度简化的风险,该方案通常是您的应用程序的名称。这是您确认该网址适用于您的应用程序的方法

在你的小部件主体中,你使用 widgetURL 修饰符:

var body: some View {
        content().widgetURL("myApp://someAction")
}
Run Code Online (Sandbox Code Playgroud)

然后在您的应用程序中,您可以使用 onOpenURL 修饰符来获取 url,检查其是否适合您的应用程序并解析它以确定要执行的操作。someAction 是您发送给应用程序以告诉它做什么的消息

 var body: some Scene {
        WindowGroup {
            ContentView()
                .onOpenURL { url in
                    guard url.scheme == "myApp" else { return }
                    print(url) // parse the url to get someAction to determine what the app needs do
                }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我通常采用 myApp://someAction/parms 形式的 url,以便我可以解析 url 以确定应用程序需要执行的操作,并向其传递一些 parms。有些人喜欢通过使用 URLComponents(路径、queryItems 等)正确形成 URL 来实现此目的。这可能是最佳实践。