【问题标题】:What UIViewController method is called when opening app from background?从后台打开应用程序时调用什么 UIViewController 方法?
【发布时间】:2011-04-08 07:09:19
【问题描述】:

是否有任何方便的方法来确定是否从处于后台模式的应用程序加载视图?

在 3.X 中,我将依赖 viewDidLoad 来进行一些初始化等操作,但是对于 4.X,情况并非如此,因为您不能依赖 viewDidLoad 方法被调用。

我想避免在 appdelegate 中添加额外的标志来检测这一点,我宁愿在 UIViewController 中使用可靠的方法来执行此操作,但似乎在 UIViewController 的生命周期中找不到任何可以帮助我的东西在这里。

有什么想法吗?你如何处理这种情况?

【问题讨论】:

    标签: uiviewcontroller background ios4 ios multitasking


    【解决方案1】:

    斯威夫特 5

    订阅通知

    
           NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    
            @objc func appMovedToForeground() {
                //Your code here
            }
    
    

    删除通知

    
        override func viewWillDisappear(_ animated: Bool) {
                super.viewWillDisappear(animated)
    
                NotificationCenter.default.removeObserver(self)
        } 
    
    

    【讨论】:

      【解决方案2】:

      UIViewController 的生命周期没有在将应用从后台移动到前台时调用的方法。

      当您希望此事件触发某些特定代码块时,您需要添加一个名为 Notification.Name.UIApplicationWillEnterForeground 的通知观察者。这方面的一个例子是:

      NotificationCenter.default.addObserver(self, selector: #selector(appMovedToForeground), name: Notification.Name.UIApplicationWillEnterForeground, object: nil)
      
      @objc func appMovedToForeground() {
          //Your code here
      }
      

      请记住,您需要移除观察者以防止它在整个应用程序中触发。

      【讨论】:

        【解决方案3】:
        - (void)viewWillAppear:(BOOL)animated
        

        不是

        - (void)viewDidLoad
        

        应用程序委托方法

        - (void)applicationWillEnterForeground:(UIApplication *)applicationUIApplicationDelegate

        将在应用程序进入前台后调用,但您可以在任何视图中为 UIApplicationWillEnterForegroundNotification 添加观察者。

        【讨论】:

        • 是的,我知道 viewWillAppear 会被调用,顾名思义,我不能将行为基于此方法,因为当视图从堆栈中弹出以显示我们正在谈论的一个。抱歉,如果我的原始帖子中不清楚这一点。
        • @Kaspa - 实际上,从后台返回时不会调用 viewWillAppear (stackoverflow.com/questions/5277940/…)
        • viewWillAppear 没有被调用。
        猜你喜欢
        • 2013-03-29
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2013-01-09
        • 1970-01-01
        相关资源
        最近更新 更多