Background/foreground application state changes in iOS 4

Question: I’ve got an iPhone app that’s mainly targetting 3.1-3.2 devices but I’d like to take advantage of iOS 4 APIs when they’re available. I’m unable to build an iPad project without generating a runtime error when the app references to “UIApplicationDidEnterBackgroundNotification” while I try to set up a custom notification listener. SDK: Xcode 4.2. What’s wrong? Answer: You are referencing to something that is not there. When your app runs on iOS 3.2 the frameworks of 4.0+ are not present, aka the null pointer and runtime error. See the example code below for a quick solution. iOS 4 supports (limited) execution in background however in iOS 3.x background execution is absolutely not supported. There are only two lifecycle state for our application in iOS 3: active or not running. In the pre iOS 4 world the exit point is the applicationWillTerminate. In iOS 4 your app will NOT receice applicationWillTerminate if it is in background and user selects force quit or shut down the device. Force quit is pressing the minus sign in the recent applications list. You will receive applicationWillTerminate (See UIApplicationDelegate Protocol Reference) if your app is in foreground and system shuts down in a controlled way like due to low battery. If your applicationWillTerminate method does not return in a timely manner, the system may kill the process altogether. When you need to save some configuration data, you have to do so in applicationWillTerminate for aging devices with OS 2.x, 3.x and, additionally, in applicationDidEnterBackground for iOS 4.0+ apps. Sample code:
// set up notification listeners in iOS4+ anywhere in your project (for example in an init method)
if ( &UIApplicationDidEnterBackgroundNotification ){
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appDidEnterBackgroundNotif:) name: UIApplicationDidEnterBackgroundNotification object: nil];
}

if ( &UIApplicationWillEnterForegroundNotification ){
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(appWillComeBackNotif:) name: UIApplicationWillEnterForegroundNotification object: nil];
}

//... handle notification in your module ...

// This method will be called when your app is about to go to background
// Listens to UIApplicationDidEnterBackgroundNotification but it is getting called only in iOS 4.0+ when the Home button is hit.
- (void) appDidEnterBackgroundNotif: (NSNotification *) notify
{
    // ...
}

// Posted when app is on its way to becoming the active application again
// Double tap the home button and again relaunch the app, then the following delegate method is called
// Listens to: UIApplicationWillEnterForegroundNotification
- (void) appWillComeBackNotif: (NSNotification *) notify
{
    // ...
}