For the More Curious: Application State Transitions

Let’s write some quick code to get a better understanding of the different application state transitions.

In AppDelegate.swift, implement the application state transition delegate methods so that they print out the name of the method. You will need to add four more methods. (Check to make sure the template has not already created these methods before writing brand new ones.) Rather than hardcoding the name of the method in the call to print(), use the #function expression. At compile time, the #function expression will evaluate to a String representing the name of the method.

func applicationWillResignActive(_ application: UIApplication) {
    print(#function)
}

func applicationDidEnterBackground(_ application: UIApplication) {
    print(#function)
    let success = itemStore.saveChanges()
    if success {
        print("Saved all of the Items")
    } else {
        print("Could not save any of the Items")
    }
}

func applicationWillEnterForeground(_ application: UIApplication) {
    print(#function)
}

func applicationDidBecomeActive(_ application: UIApplication) {
    print(#function)
}

func applicationWillTerminate(_ application: UIApplication) {
    print(#function)
}

Finally, add the same print() statement to the top of application(_:didFinishLaunchingWithOptions:).

func application(_ application: UIApplication, didFinishLaunchingWithOptions
        launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
    print(#function)
    ...
}

Build and run the application. You will see that the application gets sent application(_:didFinishLaunchingWithOptions:) and then applicationDidBecomeActive(_:). Play around to see what actions cause what transitions.

Press the Home button and the console will report that the application briefly inactivated and then went into the background state. Relaunch the application by tapping its icon on the Home screen or in the task switcher. The console will report that the application entered the foreground and then became active.

Press the Home button to exit the application again. Then, double-press the Home button to open the task switcher. Swipe the Homepwner application up and off this display to quit the application. Note that no method is called on your application delegate at this point – it is simply terminated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset