1

我正在使用 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(_:),因此我们将不胜感激任何指导。

谢谢!

4

1 回答 1

0

这是我从以前的项目中得到的东西。您可以设置一个通知观察者来检查应用程序是否已“移至后台”,因此基本上是在用户退出应用程序时。

 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")
}
于 2021-01-28T01:40:25.430 回答