I want to listen to notifications when the app goes to the background and comes back. I'm trying to use the NotificationCenter publishers and have the SwiftUI view listen to them.
I can use a few methods to do it and I'm trying to use two of them but the interesting thing is, that although all seem legit when I put the subscriber in the init()
method, it just does not work.
I tried to put it on the main
thread but still no success.
Does anyone have any idea why?
Here's my code:
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)
}
}
Strangely the listener in the onReceive
modifier works like a charm. In the init()
the print("init")
never gets called.
@State
wrapper anyway but at a certain point Xcode started complaining that in a struct you can't modify the properties. But now it accepts it. – Kunming