Created
April 18, 2020 14:28
-
-
Save DaisukeNagata/a3dd13c81526f3c8d8f3743bae6c4bd0 to your computer and use it in GitHub Desktop.
SwiftUI_NotificationCenter fore and back
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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