从 WidgetKit 小部件扩展检测应用程序启动

Detect app launch from WidgetKit widget extension

点击 WidgetKit 小部件会自动启动其父应用程序。如何检测我的应用程序是否从其 WidgetKit 小部件扩展启动?

我无法在应用程序中找到有关捕获此内容的任何文档 AppDelegate and/or SceneDelegate.

如果您正在为小部件 UI 设置小部件URL 或 Link 控件,则包含的应用程序将以 application(_:open:options:) 打开。您可以在 URL 中设置其他数据以了解来源。

如果您没有使用 widgetUrl 或 link 控件,则包含的应用程序打开 application(_:continue:restorationHandler:) 并且 userInfo 具有 WidgetCenter.UserInfoKey。那应该告诉您从小部件打开的应用程序以及有关用户交互的信息。

要检测从父应用程序支持场景的 WidgetKit 小部件扩展启动的应用程序,您需要在小部件的视图中实现scene(_:openURLContexts:), for launching from a background state, and scene(_:willConnectTo:options:), for launching from a cold state, in your parent application's SceneDelegate. Also, add widgetURL(_:)

小部件的 View:

struct WidgetEntryView: View {
    
    var entry: SimpleEntry
    
    private static let deeplinkURL: URL = URL(string: "widget-deeplink://")!

    var body: some View {
        Text(entry.date, style: .time)
            .widgetURL(WidgetEntryView.deeplinkURL)
    }
    
}

父应用程序的 SceneDelegate

// App launched
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _: UIWindowScene = scene as? UIWindowScene else { return }
    maybeOpenedFromWidget(urlContexts: connectionOptions.urlContexts)
}

// App opened from background
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    maybeOpenedFromWidget(urlContexts: URLContexts)
}

private func maybeOpenedFromWidget(urlContexts: Set<UIOpenURLContext>) {
    guard let _: UIOpenURLContext = urlContexts.first(where: { [=11=].url.scheme == "widget-deeplink" }) else { return }
    print(" Launched from widget")
}

SwiftUI 2 生命周期

  1. widgetURL 添加到您的小部件视图:
struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

    private static let deeplinkURL = URL(string: "widget-deeplink://")!

    var body: some View {
        Text("Widget")
            .widgetURL(Self.deeplinkURL)
    }
}
  1. 检测是否使用 onOpenURL 中的深层链接打开应用:
@main
struct WidgetTestApp: App {
    @State var linkActive = false

    var body: some Scene {
        WindowGroup {
            NavigationView {
                VStack {
                    NavigationLink("", destination: Text("Opened from Widget"), isActive: $linkActive).hidden()
                    Text("Opened from App")
                }
            }
            .onOpenURL { url in
                guard url.scheme == "widget-deeplink" else { return }
                linkActive = true
            }
        }
    }
}

这是一个 GitHub repository 包含不同的 Widget 示例,包括 DeepLink Widget。