从 SceneDelegate 更新屏幕结构的状态

Update state of a screen struct from SceneDelegate

我来自 react-native,是 Swift 和 SwiftUI 的初学者,我很好奇如何在特定屏幕上执行操作并更新状态该应用程序回到前台。我想检查通知的状态("allowed, "denied" 等)并更新 UI。

这是一些示例代码 - 这是我要更新的视图:

struct Test: View {
    @State var isNotificationsEnabled : Bool

    var body : some View {
        Toggle(isOn: self.isNotificationsEnabled) {
            Text("Notifications")
        }
    }

}

到目前为止,我一直在阅读的是,您需要编辑 SceneDelegate.swift 中的 func sceneWillEnterForeground(_ scene: UIScene),但是我究竟该如何更新我的 Test 结构的状态那里?我认为我们需要某种全局状态,但这只是一个猜测。

有什么建议吗?

这是最简单的方法

struct Test: View {
    @State private var isNotificationsEnabled : Bool

    private let foregroundPublisher = NotificationCenter.default.publisher(for: UIScene.willEnterForegroundNotification)

    var body : some View {
        Toggle(isOn: self.$isNotificationsEnabled) {
            Text("Notifications")
        }
        .onReceive(foregroundPublisher) { notification in
            // do anything needed here
        }
    }
}

当然,如果您的应用程序可以有多个场景并且您需要以某种方式区分它们,那么将需要这种方法的更复杂的变体来区分哪个场景生成此通知。