Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute code when app reopens

I have a Single View Application. When I hit the home button and ‘minimise’ the application I want to be able to execute code when the user reopens it.

For some reason viewDidAppear and viewWillAppear do not execute when I minimise and reopen the application.

Any suggestions?

Thanks in advance sAdam

like image 786
Adam H Avatar asked Dec 05 '22 16:12

Adam H


1 Answers

You can either execute code in the app delegate in

- (void)applicationDidBecomeActive:(UIApplication *)application

or register to observe the UIApplicationDidBecomeActiveNotification notification and execute your code in response.

There is also the notification UIApplicationWillEnterForegroundNotification and the method - (void)applicationWillEnterForeground:(UIApplication *)application in the app delegate.


To hook up notifications add this at an appropriate point

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

Define a the corresponding method

- (void)didBecomeActive:(NSNotification *)notification;
{
    // Do some stuff
}

Then don't forget to remove yourself an observer at an appropriate point

[[NSNotificationCenter defaultCenter] removeObserver:self];

Discussion

You most likely only want your viewController to respond to events whilst it is the currently active view controller so a good place to register for the notifications would be viewDidLoad and then a good place to remove yourself as an observer would be viewDidUnload

If you are wanting to run the same logic that occurs in your viewDidAppear: method then abstract it into another method and have viewDidAppear: and the method that responds to the notification call this new method.

like image 197
Paul.s Avatar answered Dec 26 '22 15:12

Paul.s