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??
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 UIViewController
s setup code:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(appDidEnterForeground) name:@"appDidEnterForeground" object:nil];
Now the method appDidEnterForeground
gets 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 UIApplicationWillEnterForeground
and 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