What happens inside UIApplicationMain, and how does @main on a SwiftUI App differ?

6.2.3 · L2 · Interview

Predict first

Which of these starts the main run loop?

// A: application(_:didFinishLaunchingWithOptions:)
// B: UIApplicationMain
// C: viewDidLoad
  • A
  • B
  • C

Mental model. UIApplicationMain is the stage manager: it sets up the stage, switches on the lights (the run loop) and then waits for events forever.

Every UIKit app starts at a main function that calls UIApplicationMain (the @main attribute on the app delegate generates it). It creates the single UIApplication object, instantiates your app delegate, loads the main storyboard if the manifest names one, starts the main run loop, and never returns. It then calls application(_:didFinishLaunchingWithOptions:), asks for a scene configuration, connects the scene and calls scene(_:willConnectTo:options:), where you build the window; the first frame is drawn when that work finishes and the render server commits it.

A SwiftUI app marks a type conforming to App with @main. The system builds the same machinery underneath: it still runs UIApplicationMain and a UIKit app delegate, but your body of Scenes is what creates the windows, so there is no storyboard or scene delegate to write. If you need an app delegate (push registration, background session events), you attach one with @UIApplicationDelegateAdaptor. Either way, the work before the first frame is on the launch path, so keep it small.

UIApplicationMain creates the application and runs the main run loop. Everything else is called from inside it.

Common traps

  • Doing heavy setup in didFinishLaunching. It delays the first frame. Defer anything not needed to draw the first screen.
  • Assuming SwiftUI has no app delegate. It still exists underneath; use the adaptor when you need it.

They might follow up with

  • Why does UIApplicationMain never return? It runs the main run loop for the life of the process.
  • Where would you put a custom main? In main.swift, calling UIApplicationMain yourself, for example to subclass UIApplication.

Related questions

  • 6.4.1 Walk through what happens from tapping the icon to the first frame.
  • 6.3.1 What is a run loop, and what happens in one iteration?
  • 6.2.4 How does the SwiftUI lifecycle map onto UIKit’s, and what is scenePhase for?

← What is a scene, and what is the split between AppDelegate and…   How does the SwiftUI lifecycle map onto UIKit’s, and what is… →