How to call viewController's method in appdelegate

489 Views Asked by At

I want viewController's method for update data.

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

how it possible?

2

There are 2 best solutions below

2
Krunal On BEST ANSWER

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)
0
Alexey Kudlay On

Use UIApplicationDidBecomeActiveNotification. See this answer.