在没有 AppDelegate 和 SceneDelegate 的新 SwiftUI 应用程序生命周期中,在我的 iOS 应用程序中的何处配置 Firebase?

Where to configure Firebase in my iOS app in the new SwiftUI App life cycle without AppDelegate and SceneDelegate?

我已经有了一个可以完全使用 SwiftUI 构建的应用程序。 我使用 Firebase 通过 Cloud Functions 进行身份验证和通知。

现在使用新的 SwiftUI App->Scene->View 构造,我无法将设置添加到我的应用程序。

例如 -> 最初的 FirebaseApp.configure() 最初会在 didFinishLaunchingWithOptions 中进入 AppDelegate,现在我不知道在哪里添加这个配置。

设置远程通知也是如此。

PS:如果需要更多 details/code 以前的应用程序,请发表评论。我没有添加任何代码,因为我觉得没有必要。

在下面的 link 上找到了答案:

hackingWithSwift

页面代码如下:

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print("Your code here")
        FirebaseApp.configure()
        return true
    }
}

并且在 App

里面

我们需要添加以下行:

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate.

解释在link.

在新的 SwiftUI 生命周期中,有三种初始化第三方框架的方法:

使用旧的生命周期模型

您仍然可以使用旧的生命周期模型:

选项 1:使用 UIKit App Delegate 生命周期

新建SwiftUI项目时,可以选择旧的生命周期模型。这将像以前一样创建一个 AppDelegate 和一个 SceneDelegate。不像一直使用 SwiftUI 那样花哨,我承认 - 但绝对是最简单和最直接的方式。

使用新的生命周期模型

如果您想使用新的生命周期模型,请使用以下任一方法。

选项 2:使用 App 的初始化程序

您可以覆盖 App class 的默认初始化程序,如下所示:

import SwiftUI
import Firebase

@main
struct SO62626652_InitialiserApp: App {
  
  init() {
    FirebaseApp.configure()
  }
  
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
  }
}

选项 3:使用 @ UIApplicationDelegateAdaptor

在你的 App class 中,定义一个 属性 来保存对你的 AppDelegate 的引用,并让 SwiftUI 使用 AppDelegate 注入 AppDelegate =16=] 属性 包装器,像这样:

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
  }
}