Where to configure Firebase in my iOS app in the new SwiftUI App life cycle without AppDelegate and SceneDelegate?
There are three approaches for initialising third part frameworks in the new SwiftUI life cycle:
Using the old life cycle model
You can still use the old life cycle model:
Option 1: Use the UIKit App Delegate life cycle
When creating a new SwiftUI project, you can choose the old life cycle model. This will create an AppDelegate
and a SceneDelegate
as before. Not as fancy as using SwiftUI all the way, I admit - but definitely the easiest and most straightforward way.
Using the new life cycle model
If you want to use the new life cycle model, use either one of the following approaches.
Option 2: Use the App
's initialiser
You can override the default initialiser of your App
class, like this:
import SwiftUI
import Firebase
@main
struct SO62626652_InitialiserApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Option 3: Use @ UIApplicationDelegateAdaptor
In you App
class, define a property that holds a reference to your AppDelegate
, and let SwiftUI inject the AppDelegate
using the @ UIApplicationDelegateAdaptor
property wrapper, like this:
import SwiftUI
import Firebase
@main
struct SO62626652_AppDelegateAdaptorApp: App {
@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}