swift - 如何检测 ViewController 应用程序从什么进入后台?

swift - How to detect from what ViewController application enter background?

在我的 swift 应用程序中,我需要知道我的应用程序从哪个屏幕进入后台。我正在尝试以这种方式使用 NotificationCenter

class MainViewController: UIViewController{
   override func viewDidLoad() {
        super.viewDidLoad()
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundMain), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    @objc func appMovedToBackgroundMain() {
        print("main - App moved to Background!")
    }
}

class InitViewController: UIViewController{
       override func viewDidLoad() {
            super.viewDidLoad()
            let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(appMovedToBackgroundInit), name: UIApplication.didEnterBackgroundNotification, object: nil)
        }

        @objc func appMovedToBackgroundInit() {
            print("init - App moved to Background!")
        }
    }

当我在 MainViewController 按下 Home 按钮时,我进入了 Xcode 的控制台这些行:

init - App moved to Background!
main - App moved to Background!

我预计那里只有一行 - main - App moved to Background!。我怎样才能做到这一点?

您可以使用以下函数:

 func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

在这里您可以查看导航控制器的控制器中哪个控制器位于顶部。

print(self.navigationController.topViewController)

关于AppDelegate Methods: applicationDidEnterBackground or applicationWillEnterForeground, 你可以得到最顶层的UIViewController。在这个问题上有很好的解释:Get top most UIViewController

当应用程序进入后台状态时,下面的方法将被调用。

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}