Application lifecycle demo for Xamarin.iOS

This article and sample code demonstrates the four application states in iOS, and the role of the AppDelegate methods in notifying the application of when states get changed. The application will print updates to the console whenever the app changes state:

The sample app

The app will print updates to the console whenever the app changes state

Walkthrough

  1. Open the Lifecycle project in the LifecycleDemo solution.

  2. Open up the AppDelegate class. Logging has been added to the lifecycle methods to indicate when the application has changed state:

    public override void OnActivated(UIApplication application)
    {
        Console.WriteLine("OnActivated called, App is active.");
    }
    public override void WillEnterForeground(UIApplication application)
    {
        Console.WriteLine("App will enter foreground");
    }
    public override void OnResignActivation(UIApplication application)
    {
        Console.WriteLine("OnResignActivation called, App moving to inactive state.");
    }
    public override void DidEnterBackground(UIApplication application)
    {
        Console.WriteLine("App entering background state.");
    }
    // not guaranteed that this will run
    public override void WillTerminate(UIApplication application)
    {
        Console.WriteLine("App is terminating.");
    }
    
  3. Launch the application in the simulator or on the device. OnActivated will be called when the app launches. The application is now in the Active state.

  4. Hit the Home button on the simulator or device to bring the application to the background. OnResignActivation and DidEnterBackground will be called as the app transitions from Active to Inactive and into the Backgrounded state. Since there is no application code set to execute in the background, the application is considered suspended in memory.

  5. Navigate back to the app to bring it back into the foreground. WillEnterForeground and OnActivated will both be called:

    State changes printed to the console

    The following line of code in the view controller is executed when the application has entered the foreground from the background, and changes the text displayed on the screen:

    UIApplication.Notifications.ObserveWillEnterForeground ((sender, args) => {
        label.Text = "Welcome back!";
    });
    
  6. Press the Home button to put the application into the background. Then, double-tap the Home button to bring up the application switcher. On the iPhone X, swipe up from the bottom of the screen:

    The application switcher

  7. Locate the application in the App Switcher, and swipe up to remove it (on iOS 11, long press until the red icons appear in the corner):

    Swipe up to remove a running app

iOS will terminate the application. Note that WillTerminate is not called because application is already suspended in the background.