全局监听
Text("Hello, World!")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
print("即将进入后台")
}.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
print("即将进入前台")
}.onReceive(NotificationCenter.default.publisher(for: UIApplication.userDidTakeScreenshotNotification)) { _ in
print("用户截屏了")
}.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
print("已经进入后台")
}.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
print("已经进入前台")
}.onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { _ in
print("程序将要销毁")
}
监听单个页面
@Environment(\.scenePhase) private var scenePhase
.onChange(of: scenePhase) { newScenePhase in
if newScenePhase == .background {
print("App entered the background")
}
if newScenePhase == .active {
print("App entered the foreground")
}
}