问题描述
我正在使用 Swift UI 2.0,目前的设置如下:
@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
WindowGroup {
InitialView()
}
.onChange(of: scenePhase) { (newScenePhase) in
switch newScenePhase {
case .active:
print("scene is now active!")
case .inactive:
print("scene is now inactive!")
case .background:
print("scene is now in the background!")
@unknown default:
print("sus")
}
}
}
}
这很好,但这些都不能解释应用程序终止时的情况(即用户双击主页按钮并在应用程序上向上滑动)。我该如何解释这种情况?
我尝试实施 applicationWillTerminate(_:)
失败,因此我们将不胜感激。
谢谢!
解决方法
这是我从以前的项目中获取的内容。 您可以设置一个通知观察器来检查应用程序是否已“移至后台”,因此基本上是在用户退出应用程序时。
init() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,selector: #selector(appMovedToBackground),name: UIApplication.willResignActiveNotification,object: nil)
}
只需将其放入主视图控制器的 init 方法中,然后...
@objc func appMovedToBackground() {
print("App moved to background")
}