当应用程序转到后台并返回时,我想听通知。我正在尝试使用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")从不被调用。
发布于 2020-01-01 13:11:00
@State还没有准备好在init中,所以它不能用于这样的目的。办法如下:
var cancellables = Set<AnyCancellable>()
init() {
NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)
.sink(receiveValue: { _ in
print(">> in init")
})
.store(in: &cancellables)
}在这样定义的cancellables中,您可以存储在init中创建的所有订阅者,但是您以后将无法在代码中使用它,但是这种方法对于一旦定义好的通知处理程序是很好的。
发布于 2020-01-16 13:16:45
你能用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的替代品
https://stackoverflow.com/questions/59552487
复制相似问题