【问题标题】:SwiftUI communication between AppDelegate and ContentView()AppDelegate 和 ContentView() 之间的 SwiftUI 通信
【发布时间】:2020-05-16 05:01:15
【问题描述】:

我在 SwiftUI 应用程序上收到了一个静默远程通知。它不是由 UNUserNotificationCenter 拾取的,而是由旧的 AppDelegate didReceiveNotification 函数拾取的。通知 ContentView() 发生更改的解决方案是什么? AppDelegate 中的 ObservableObject?

【问题讨论】:

    标签: swiftui cloudkit remote-notifications


    【解决方案1】:

    您可以在 AppDelegate 中声明一个符合 ObservableObject 的商店,并将其设置为 ContentView 的环境对象。

    // AppDelegate.swift
    // in the class
    let store = Store()
    
    // in the applicationDidFinishLaunching(_:) method
    window.contentView = NSHostingView(rootView: contentView.environmentObject(store))
    
    // ContentView.swift
    // in the struct
    @EnvironmentObject var store: Store
    

    环境对象是一个引用,因此您可以将值传递给它。与使用ObservableObject 相同。完成更新后,只需调用objectWillChange.send() 或将属性标记为@Published。 ContentView 将在通知后更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多