How can I use applicationDidBecomeActive in UIViewController?

Viewed 64083

I want to reload data in UIViewController when application become active or become foreground.

I know applicationDidBecomeActive is called in AppDelegate class.
But I have to have a global variable for the UIViewController to reload its data in AppDelegate class like this code:

in AppDelegate.m

// global variable
UIViewController *viewController1;
UIViewController *viewController2;

-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [viewController1 reloadData];
    [viewController2 reloadData];
}

But it is inconvenient especially when I have a lot of UIViewControllers.

Can I use applicationDidBecomeActive in UIViewController instead of in AppDelegate class?
Or are there better ways than having global variable for UIViewController?

I also need to use the following method from UIViewControllers:

-(void)applicationWillResignActive:(UIApplication *)application
-(void)applicationDidEnterBackground:(UIApplication *)application
-(void)applicationWillEnterForeground:(UIApplication *)application
6 Answers

update for swift 5

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)

    }
   // remove the observer 
   deinit {

       print("Receiver teardown")

       NotificationCenter.default.removeObserver(self)

   }

    @objc func applicationDidBecomeActive(notification: NSNotification) {
        // Application is back in the foreground

        print("applicationDidBecomeActive")
    }

}
Related