How to call method when app enters foreground from background

user3542888 picture user3542888 · May 19, 2014 · Viewed 7.4k times · Source

Is there a simple way to call a method when my app enters the foreground from the background? I have my program call a method "nowYouSeeMe" in the viewDidLoad method, which works great when running the app the first time. When I use the app and then hit home-button it moves to the background as usual. Now when I press app icon and it brings it to the foreground I basically want it to call the nowYouSeeMe method again.

-(void)nowYouSeeMe{
  NSLog(@"I'm back");
}

Any ideas??

Answer

iCaramba picture iCaramba · May 19, 2014

As already mentioned there is - (void)applicationDidBecomeActive:(UIApplication *)application;in App Delegate, but most of the time you need the information not in your app delegate but your view Controller. Therefore you can use NSNotificationCenter. In your app delegate you could do the following:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotification:[NSNotification notificationWithName:@"appDidEnterForeground" object:nil]];

Now you can set up listeners in your UIViewControllers setup code:

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(appDidEnterForeground) name:@"appDidEnterForeground" object:nil];

Now the method appDidEnterForegroundgets called on your view controller whenever the app enters the foreground.

But you don't even need to post the notification yourself because it is already defined in UIApplication. If you scroll down the documentation (UIApplication Class Reference) you see all the notifications declared in UIApplication.h, in your case UIApplicationWillEnterForegroundNotification. Notice the difference between UIApplicationWillEnterForegroundand UIApplicationDidEnterForeground, but most times you want to use UIApplicationWillEnterForeground, just to set everything up and be ready when the app is displayed.

Of course you should define a constant somewhere for your notifcationname and if you don't need the observer anymore remove it.

Edit: you could also use @selector(nowYouSeeMe) as in your question, missed that