点击WidgetKit WidgetKit 会自动启动其父应用程序。如何检测我的应用程序是否从其WidgetKit WidgetKit 扩展启动?
我在应用程序AppDelegate和/或SceneDelegate中找不到有关捕获此文件的任何文档。

最佳答案

要从父应用程序支持场景的WidgetKit WidgetKit 扩展中检测应用程序启动,您需要在父应用程序的SceneDelegate中实现scene(_:openURLContexts:)(从后台状态启动)和scene(_:willConnectTo:options:)(从冷状态启动)。另外,将widgetURL(_:)添加到窗口 WidgetKit 的 View 中。
WidgetKit 的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: { $0.url.scheme == "widget-deeplink" }) else { return }
    print("🚀 Launched from widget")
}

10-06 05:28