【发布时间】:2020-01-01 12:26:07
【问题描述】:
我想在应用程序进入后台并返回时收听通知。我正在尝试使用 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") 永远不会被调用。
【问题讨论】:
标签: swiftui combine notificationcenter