Calling a method when the application is called from background

3.8k Views Asked by At

In applications like Foursquare when I click the Home button the application goes to background. Then when I click on its icon, it loads back the content on the screen.

When I send my app to background and then I recall it back, it doesn't load back the content to the screen. I have entered my code in the viewDidAppear method but it is not executed.

How is it possible to load the application content when it becomes active?

3

There are 3 best solutions below

1
On

You need to respond to - (void)applicationDidBecomeActive:(UIApplication *)application or - (void)applicationWillEnterForeground:(UIApplication *)application or the equivalent UIApplication notifications. The UIViewController lifecycle calls like viewDidAppear aren't triggered by app lifecycle transitions.

2
On

smparkes suggestion is right. You could register for UIApplicationDidBecomeActiveNotification or UIApplicationWillEnterForegroundNotification. These notifications are called after those method (the ones smparkes wrote) are called. In the handler for this notification do what you want. For example in viewDidLoad for your controller register the following notification:

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

Do not forget to remove in dealloc:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Finally, doUpdate method could be the following

-(void)doUpdate:(NSNotification*)note
{
    // do your stuff here...
}

I suggest you to read UIApplicationDelegate class reference. In particular read about Monitoring Application State Changes.

Hope it helps.

0
On

Suppose you want to listen to UIApplicationDidBecomeActiveNotification,here is the ObjC code that might help you.

[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidBecomeActiveNotification
object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {

    // custom code goes here.
}];