首页 > 解决方案 > swift - 如何检测从哪个 ViewController 应用程序进入后台?

问题描述

在我的 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!")
        }
    }

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

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

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

标签: swiftnsnotificationcenter

解决方案


在 AppDelegate Methods:applicationDidEnterBackgroundapplicationWillEnterForeground上,您可以获得最顶层的 UIViewController。在这个问题上有很好的解释:Get top most UIViewController


推荐阅读