So I'm watching some videos about how to setup Firebase with SwiftUI but none of them really seem to be the most recent?
The latest video I found just does two steps, importing Firebase
, then making an init in my app struct that calls FirebaseApp.configure()
like this:
import SwiftUI
import Firebase
@main
struct FirestoreDemoApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
But Firebase has a bunch of code and tells me to set it up like this:
import SwiftUI
import FirebaseCore
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
FirebaseApp.configure()
return true
}
}
@main
struct YourApp: App {
// register app delegate for Firebase setup
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
var body: some Scene {
WindowGroup {
NavigationView {
ContentView()
}
}
}
}
But both of those still seem to work? Could someone maybe explain what exactly the second one is with all this AppDelegate and what's the point of it? Why is the first option which is much shorter also working just fine?
CodePudding user response:
Firebaser here - actually, I am the person who made the change to our onboarding flow that recommends using the @UIAppDelegateAdaptor
approach.
TL;DR: Both approaches work fine, but the @UIAppDelegateAdaptor
approach covers more use cases.
Initialising Firebase in your app's initialiser works for most of Firebase's APIs, such as Firestore, RTDB, (most of) Authentication, etc. However, some APIs, such as FCM or Phone Number Authentication need an App Delegate.
Since we didn't want to make the onboarding flow more complicated than necessary (e.g. by asking people if they are planning to use FCM or Phone Auth, or making them read a lengthy blog post), we decided to take the safe route and recommend the slightly more complicated-looking approach that covers all use cases.
For an even more detailed explanation, check out my blog post, Firebase and the new SwiftUI 2 Application Life Cycle.