带有 NotificationCenter 发布者的 SwiftUI

SwiftUI with NotificationCenter publishers

我想在应用程序进入后台并返回时收听通知。我正在尝试使用 NotificationCenter 发布者并让 SwiftUI 视图收听它们。
我可以使用几种方法来做到这一点,我正在尝试使用其中的两种,但有趣的是,尽管当我将订阅者放入 init() 方法时一切看起来都是合法的,但它就是行不通。
我试着把它放在 main 线程上,但仍然没有成功。
有人知道为什么吗?
这是我的代码:

struct ContentView: View {
    @State var isActive = true
    @State var cancellables = Set<AnyCancellable>()
    var body: some View {
        ZStack {
            Image("background")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)                        
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
            self.isActive = false
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification), perform: {_ in
            self.isActive = true
        })
    }

    init() {
        NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
         //   .receive(on: RunLoop.main)
            .sink(receiveValue: { _ in
                print("init")
            }
            .store(in: &cancellables)
    }
}

奇怪的是,onReceive 修饰符中的侦听器非常有效。在 init() 中,print("init") 永远不会被调用。

@State 尚未在初始化中准备好,因此不能用于此类目的。做法可以如下:

var cancellables = Set<AnyCancellable>()
init() {
    NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
        .sink(receiveValue: { _ in
            print(">> in init")
        })
        .store(in: &cancellables)
}

在这样定义的 cancellables 中,您可以存储在 init 中创建的所有订阅者,但稍后您将无法在代码中使用它,但这种方法适用于一次定义的通知处理程序。

可以使用onAppear吗?

...
...
  var body: some View {
  ... your body code
  }.onAppear(perform: loadNotification)

  private func loadNotification() {
     NotificationCenter.default.publisher(
     ....
  }

参见onAppear

https://developer.apple.com/documentation/swiftui/view/3278614-onappear

它似乎是 viewDidLoad

的替代品