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

时间:2019-01-29 11:34:30

标签: swift nsnotificationcenter

在我的快捷应用程序中,我需要知道应用程序从哪个屏幕进入后台。我试图以这种方式使用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!")
        }
    }

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用以下功能:

 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)

答案 1 :(得分:1)

在AppDelegate的方法:applicationDidEnterBackgroundapplicationWillEnterForeground,你可以得到最顶端的UIViewController。据在这个问题上很好地解释:Get top most UIViewController

答案 2 :(得分:0)

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

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.
}