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)
如果您正在为小部件 UI 设置小部件 URL 或链接控件,则包含的应用程序将使用application(_:open:options:). 您可以在 URL 中设置其他数据以了解来源。
如果您不使用 widgetUrl 或链接控件,则包含应用程序将打开application(_:continue:restorationHandler:)并userInfo具有WidgetCenter.UserInfoKey. 这应该告诉您从小部件打开的应用程序以及有关用户交互的信息。
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)
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。