views:

135

answers:

1

Hi,

how one can detect that the app just return from "background mode"? I mean, I don't want my app to fetch data (each 60 sec) when the user press the "home button". But, I'd like to make some "special" update the first time the app is in foreground mode.

How to detect this two events :

  1. app going to background mode (or "is this app in background mode" ?)
  2. app going to foreground mode ?

Thanks in advance.

François

+1  A: 

Here's how to listen for such events:

// Register for notification when the app shuts down
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillTerminateNotification object:nil];

// On iOS 4.0+ only, listen for background notification
if(&UIApplicationDidEnterBackgroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationDidEnterBackgroundNotification object:nil];
}

// On iOS 4.0+ only, listen for foreground notification
if(&UIApplicationWillEnterForegroundNotification != nil)
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFunc) name:UIApplicationWillEnterForegroundNotification object:nil];
}

Note, the if checks ensure that your code will work on iOS 4.x and also on iOS 3.x - if you build against the iOS 4.x SDK and set the deployment target to iOS 3.x your app can still run on 3.x devices but the relevant symbols will be nil, and therefore it won't try to ask for notifications that don't exist on 3.x devices (which would crash the app).

jhabbott
thanks for quick answer!
Francois B.