
SwiftUI Lifecycle 🚀
SwiftUI introduces a new app lifecycle that replaces AppDelegate
and SceneDelegate
. Instead of relying on UIKit’s UIApplication
, SwiftUI apps use the App
protocol to manage their lifecycle.
1️⃣ SwiftUI App
Lifecycle (@main
)
🔹 The entry point of a SwiftUI app is a struct conforming to the App
protocol.
🔹 It uses @main
to indicate the starting point of the app.
✅ Example
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
📌 How It Works
@main
marks this struct as the app’s entry point.WindowGroup
creates a new window for the app.ContentView()
is the initial screen.
🔥 No AppDelegate
or SceneDelegate
needed! 🎉
2️⃣ App Lifecycle Methods
SwiftUI doesn’t have AppDelegate
methods like applicationDidEnterBackground(_:)
, but it provides an alternative via @Environment(\.scenePhase)
.
✅ Detect App State Changes
import SwiftUI
@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase var body: some Scene {
WindowGroup {
ContentView()
}
.onChange(of: scenePhase) { newPhase in
switch newPhase {
case .active:
print("App is active 🟢")
case .inactive:
print("App is inactive 🟡")
case .background:
print("App is in background 🔴")
@unknown default:
print("Unknown state 🤔")
}
}
}
}
📌 App Phases
.active
→ App is in the foreground.inactive
→ App is about to go inactive (e.g., phone call).background
→ App moves to the background
3️⃣ AppDelegate
in SwiftUI (If Needed)
You can still use UIApplicationDelegate
inside SwiftUI if required.
✅ Example: Using AppDelegate
import SwiftUI
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
print("App launched 🚀")
return true
}
}@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene {
WindowGroup {
ContentView()
}
}
}
📌 When to Use AppDelegate?
✅ Firebase, Push Notifications, Background Tasks
✅ Handling deep links
✅ Custom app-wide configurations
4️⃣ Lifecycle Comparison: UIKit vs SwiftUI
Feature UIKit (AppDelegate
)SwiftUI (@main
)Entry Point@UIApplicationMain@main
in App
Window CreationUIWindow
+ SceneDelegateWindowGroup
App State HandlingAppDelegate
methods@Environment(\.scenePhase)
Background TasksapplicationDidEnterBackgroundscenePhase == .background
Multiple WindowsUISceneWindowGroup
🛠️ Key Takeaways
✅ SwiftUI eliminates the need for AppDelegate
& SceneDelegate
✅ Uses @main
for declarative app structure
✅ @Environment(\.scenePhase)
replaces AppDelegate
lifecycle methods
✅ UIApplicationDelegateAdaptor
allows legacy UIKit integration