ios - 从 WidgetKit WidgetKit 扩展检测应用程序启动

标签 ios swift swiftui ios14 widgetkit

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

最佳答案

要检测来自 WidgetKit WidgetKit 扩展的应用程序启动,其中父应用程序支持场景,您需要实现 scene(_:openURLContexts:) ,用于从后台状态启动,以及 scene(_:willConnectTo:options:) ,用于从冷状态启动,在您的父应用程序的 SceneDelegate 中.另外,添加 widgetURL(_:)到您的 WidgetKit 的 View 。
小工具的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")
}

关于ios - 从 WidgetKit WidgetKit 扩展检测应用程序启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63697132/

相关文章:

swift - 在 swift 5.1 类中使用属​​性包装器时出错

ios - FBSDKLoginManager 不处理 logInWithPublishPermissions : correctly

ios - 如何在iOS中实现固定侧边导航?

ios - Xcode 应用程序 uploader 突然说图标丢失

ios - 在使用共享扩展时从 swift 检索图像到 typescript

ios - 如何在 Swift 中调整图像大小?

swift - 如何根据 Collection View 中的单元格选择来控制 TableView 的内容?

ios - 在 NavigationView 前面放置可交互的 View 隐藏导航栏

ios - XCode 6 不允许我在 UIView 上设置自动布局约束。我究竟做错了什么?

xcode - UITextView 的 SwiftUI Wrapper 未更新 ObservedObject