What Are iOS App Lifecycle Methods
What Are iOS App Lifecycle Methods
Let’s Start
We start with an almost empty project with one screen:
Our goal is to implement lifecycle methods and then see in what order they are called. In
addition, we also want to know what each method is best suited for. Before we start exploring
the code, let’s recap the states of any iOS app:
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, willFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print(#function)
return true
}
import UIKit
With method descriptions done, now let’s examine the sequence and conditions based on which
these methods are called.
To see the name of each method that was called, we include the print(#function) command
inside each of the methods we added in the AppDelegate and SceneDelegate:
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
print(#function)
return true
}
print(#function)
return true
}
import UIKit
Now we can easily test the execution of these methods. First, we will test it on iOS 13+
Simulator, then on iOS 12 one.
● Close app:
● Move the app to background instead of closing:
Testing on iOS 12
● Launch app:
● Close app:
● Move the app to background instead of closing:
● Return to the app from the background:
Examining the difference
As we see above, the execution differs in some of the phases.
1. When the app was launched on iOS 13+, these methods were run:
● application(_:willFinishLaunchingWithOptions:),
● application(_:didFinishLaunchingWithOptions:),
● scene(_:willConnectTo:options:),
● sceneWillEnterForeground(_:),
● sceneDidBecomeActive(_:).
● application(_:willFinishLaunchingWithOptions:),
● application(_:didFinishLaunchingWithOptions:),
● applicationDidBecomeActive(_:).
● sceneWillResignActive(_:)
● sceneDidDisconnect(_:)
● applicationWillTerminate(_:)
● applicationWillResignActive(_:)
● applicationDidEnterBackground(_:)
● applicationWillTerminate(_:)
Here we notice that on iOS 12, the app was moved to background prior to getting terminated,
while on iOS 13+ the covariant method sceneDidEnterBackground(_:) was not called.
3. On iOS 13+, when the app was simply dismissed instead of terminated, these methods were
run:
● sceneWillResignActive(_:)
● sceneDidEnterBackground(_:)
On iOS 12:
● applicationWillResignActive(_:)
● applicationDidEnterBackground(_:)
In this phase we do not notice any difference since as the official documentation says, the
application methods of iOS 12 and prior were replaced by the scene ones of iOS 13 and
onward.
4. On iOS 13+, when we moved the app back to active state from the background, we saw the
following methods printed:
● sceneWillEnterForeground(_:)
● sceneDidBecomeActive(_:)
On iOS 12:
● applicationWillEnterForeground(_:)
● applicationDidBecomeActive(_:)
Resources
The source code is available on GitHub.