Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save DaisukeNagata/a3dd13c81526f3c8d8f3743bae6c4bd0 to your computer and use it in GitHub Desktop.
Save DaisukeNagata/a3dd13c81526f3c8d8f3743bae6c4bd0 to your computer and use it in GitHub Desktop.
SwiftUI_NotificationCenter fore and back
import SwiftUI
struct ContentView: View {
@State var model = OrientationModel()
var body: some View {
VStack {
Text("Hello, World!")
}
.onAppear {
self.model.contentView = self
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
final class OrientationModel: ObservableObject {
var contentView: ContentView?
private var notificationCenter: NotificationCenter
init(center: NotificationCenter = .default) {
notificationCenter = center
notificationCenter.addObserver( self, selector: #selector(foreGround), name: UIApplication.willEnterForegroundNotification,object: nil)
notificationCenter.addObserver( self, selector: #selector(backGround), name: UIApplication.didEnterBackgroundNotification,object: nil)
}
deinit {
notificationCenter.removeObserver(self)
}
@objc func foreGround(notification: Notification) {
print(notification, "foreGround")
}
@objc func backGround(notification: Notification) {
print(notification, "backGround")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment