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

Dan*_*orm 11 ios swift widgetkit swiftui ios14

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

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

Dan*_*orm 21

要从 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)
    }
    
}
Run Code Online (Sandbox Code Playgroud)

父应用程序的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")
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么应用程序不支持场景委托?可以从AppDelegate实现吗? (5认同)
  • 对于 Objective C 及更旧的项目,您可以使用此函数来拦截 URL `- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary&lt;UIApplicationOpenURLOptionsKey,id&gt; *)options` (2认同)

kth*_*rat 6

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

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


paw*_*222 5

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)
    }
}
Run Code Online (Sandbox Code Playgroud)
  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
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个GitHub 存储库,其中包含不同的 Widget 示例,包括 DeepLink Widget。