当应用程序进入前台时,哪个视图控制器处于活动状态?

Which View Controller is active when app comes to foreground?

通常情况下,当视图控制器出现

时,我可以发现
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
}

虽然如果用户按下主页按钮或出于某些其他原因应用程序进入后台然后 returns 进入前台,则不会调用此方法。要了解应用程序何时进入前台,我可以向通知中心添加一个观察者。

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        print("FirstViewController")
    }

    @objc func appWillEnterForeground() {
        print("app in foreground")
    }
}

但是,我的问题是我有一个选项卡式应用程序,我想知道当该应用程序返回前台时哪个视图控制器处于活动状态。通知中心只是发送一般消息。即使我在第一个选项卡中设置了通知观察器,当应用程序进入后台时它也可以在任何选项卡上。

使用 Notification Observer 和您的 appWillEnterForeground() 或在选项卡控制器 下的所有视图控制器中从观察器触发的任何事件。因此,无论您返回哪个视图控制器,都会在该特定 VC 中触发您的通知事件。如果你正在寻找一个集中的解决方案,这种分散枪的方法可能行不通。

NSNotification.Name.UIApplicationWillEnterForeground 是通知中心抛出的通知。很明显,这与任何特定的 VC 无关。你可以做的是

@objc func appWillEnterForeground() {
    if self.viewIfLoaded?.window != nil {
        // viewController is visible
    }
}

虽然 App 进入前台的通知会被每个 viewController 观察到它触发,但只有当前加载和可见的 VC 才会在 if 条件下执行其代码。这使您可以控制哪个 VC 当前可见。

编辑 1:

你想弄清楚的是TabBarController导航栈的顶部ViewController当应用程序来到前台时,你可以只在[=]中添加NSNotification.Name.UIApplicationWillEnterForeground的观察者15=] 并在

@objc func appWillEnterForeground() {
    var vc : UIViewController = tabBarController.viewControllers![tabBarController.selectedIndex]
    while vc.presentedViewController != nil || self.childViewControllers.count != 0 {
        if vc.presentedViewController != nil {
            vc = vc.presentedViewController!
        }
        else {
            vc = vc.childViewControllers.last!
        }
    }
    print("\(vc) should be the top most vc")
}