首页 > 解决方案 > 从 WidgetKit 小部件扩展检测应用程序启动

问题描述

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

我无法在应用程序AppDelegate和/或SceneDelegate.

标签: iosswiftswiftuiios14widgetkit

解决方案


要检测从父应用程序支持场景的 WidgetKit 小部件扩展中启动的应用程序,您需要实现scene(_:openURLContexts:)以从后台状态启动,以及实现scene(_:willConnectTo:options:)以启动从冷状态,在您的父应用程序的SceneDelegate. 此外,将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: { $0.url.scheme == "widget-deeplink" }) else { return }
    print(" Launched from widget")
}

推荐阅读