2

单击按钮时,我有一个视图控制器,我将用户带到应用程序设置。

 UIApplication.openApplicationSettings()

当我从 appsettings 回到 app 时, viewwillappear 方法不会触发。

或者是否有任何其他方法可以让我们知道 appsettings 已关闭并且用户现在正在查看屏幕。

4

2 回答 2

2

您应该使用应用程序生命周期事件(SceneDelegate/AppDelegate),而不是查看控制器生命周期事件(viewDidLoad、、viewDidAppear等)。sceneDidBecomeActive(_:)应该适合您的目的 - 对于 iOS 13+,您应该使用SceneDelegate来收听场景阶段,例如进入设置(变为非活动状态)然后返回(再次变为活动状态)。

/// SceneDelegate.swift
func sceneDidBecomeActive(_ scene: UIScene) {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.

    /// your code here
}

如果您想sceneDidBecomeActive直接在视图控制器中收听,请尝试收听didActivateNotification通知。

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        NotificationCenter.default.addObserver( /// add observer
            self,
            selector: #selector(activated),
            name: UIScene.didActivateNotification,
            object: nil
        )
    }
    
    @objc func activated() {
        print("View controller is back now")
    }
}
于 2021-09-08T16:13:44.980 回答
2

订阅以下 appdelegate 事件

applicationDidBecomeActive 

或者

applicationWillEnterForeground

在 ViewDidLoad 使用下面的代码片段

NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

并使用以下方法

  @objc func applicationDidBecomeActive(notification: NSNotification) {
        updateTableUI()
    }

移除观察者

   deinit {
           NSNotificationCenter.defaultCenter().removeObserver(self)
   }
于 2021-09-08T16:14:12.500 回答