What's the most efficient way to refresh a tableView every time the app is pushed back to the foreground?

杀马特。学长 韩版系。学妹 提交于 2019-12-02 07:55:12

Don't put any code in the app delegate. Have the view controller register to receive notifications when the app enters the foreground.

Add this in viewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(enteringForeground), name: UIApplication.willEnterForegroundNotification, object: nil)

Then add:

@objc func enteringForeground() {
    deleteOldAlarms {
        DispatchQueue.main.async {
            tableView.reloadData()
        }
    }
}

As of iOS 13, you should register for UIScene.willEnterForegroundNotification. If your app needs to work under iOS 13 as well as iOS 12 then you need to register for both notifications but you can use the same selector.

You can use NSNotification

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

In didBecomeActive call tableView.reloadData(), that should be all. You should remember to unregister the observer in deinit.

NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!