How to tell the active view controller when applicationDidBecomeActive is called?

David John picture David John · Apr 28, 2012 · Viewed 19.5k times · Source

I feel I am missing a trick here...

I just want to call viewDidLoad or viewDidAppear on the current active view controller when applicationDidBecomeActive gets called, so I can reset some animations or whatever, when the app is started up again from the background. Some of my views don't care, but others really need to know.

I am using Storyboards and my app delegate file has the standard functions - but all with EMPTY bodies. For example, didFinishLaunchingWithOptions just returns YES and does nothing else. Storyboard automagically does everything I guess.

So how can I talk to the current view controller from my rather blank, information free, app delegate?

Answer

Ben Baron picture Ben Baron · Jun 12, 2012

Instead of sending a notification from your app delegate, the OS sends a notification automatically that you can observe:

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(initSongInfo)
                                      name:UIApplicationDidBecomeActiveNotification
                                      object:nil];

and of course make sure to stop observing sometime before or inside your dealloc method, by calling:

[[NSNotificationCenter defaultCenter] removeObserver:self 
                                      name:UIApplicationDidBecomeActiveNotification 
                                      object:nil];