Search code examples
iosswiftappdelegatensnotificationapplication-lifecycle

How to call viewController's method in appdelegate


I want viewController's method for update data.

So I want use viewController's update method when applicationDidBecomeActive(_ application: UIApplication).

how it possible?


Solution

  • This may help you (tested in Swift 4)

    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(applicationDidBecomeActive),
                                                   name: Notification.Name.UIApplicationDidBecomeActive,
                                                   object: nil)
        }
    
    }
    
    @objc func applicationDidBecomeActive() {
        print("UIApplicationDidBecomeActive")
    }
    

    Note: Don't forget to remove observer when your view controller is no longer in use/memory (as this is an application level observer and will be called every time your application becomes active, whether your view controller is active or not.

    Here is code to remove observer:

    NotificationCenter.default.removeObserver(self,
                                              name: Notification.Name.UIApplicationDidBecomeActive,
                                              object: nil)