ios - 从 WidgetKit 小部件扩展检测应用程序启动
问题描述
点击 WidgetKit 小部件会自动启动其父应用程序。如何检测我的应用程序是否是从其 WidgetKit 小部件扩展启动的?
我无法在应用程序AppDelegate
和/或SceneDelegate
.
解决方案
要检测从父应用程序支持场景的 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")
}
推荐阅读
- azure-devops - Azure DevOps - 将类库项目链接到另一个项目的发布
- c# - 如何推断 lambda 参数?
- javascript - JS 下拉输入表单验证问题
- apache - 根据apache中的http头转发http请求
- swiftui - 如何计算列表中的行数?SwiftUI
- c++ - 初始化对非实例化对象的引用会导致 C++ 中的内存泄漏吗?
- google-sheets - 如何在 Google 表格中引用插入的行?
- c# - 使用固定缓冲区将字节数组重新解释为托管结构
- django - Django页面更新不刷新,页面只显示base.html
- sql - 使用 IN 将值数组与数据表进行比较