Search code examples
iosiphoneswiftxcode-storyboard

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


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?


Solution

  • I would recommend using notifications.

    In your app delegate's applicationdidBecomeActive method put in this code:

    [[NSNotificationCenter defaultCenter] postNotificationName:@"appDidBecomeActive" object:nil];
    

    In your current active view controller's init method subscribe to the notification.

    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(updateStuff)        
                                                 name:@"appDidBecomeActive" 
                                               object:nil];
    

    Implement the "updateStuff" method in your controller and you should be able to do whatever you want when the app becomes active.