在没有AppDelegate和SceneDelegate的新SwiftUI App生命周期中,哪里可以在我的iOS应用中配置Firebase?

时间:2020-06-28 18:32:15

标签: firebase firebase-authentication swiftui swiftui-environment

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

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

例如->最初的FirebaseApp.configure()最初会放在didFinishLaunchingWithOptions的{​​{1}}中,现在我不知道在何处添加此配置。

设置远程通知也是如此。

PS:如果需要先前应用程序的更多详细信息/代码,请发表评论。我没有添加任何代码,因为我觉得这是不必要的。

2 个答案:

答案 0 :(得分:23)

在新的SwiftUI生命周期中,可以使用三种方法来初始化第三方框架:

使用旧的生命周期模型

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

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

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

Setting up a SwiftUI 2.0 project with the traditional AppDelegate Life Cycle

使用新的生命周期模型

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

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

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

import SwiftUI
import Firebase

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

选项3:使用@ UIApplicationDelegateAdaptor

在您的App类中,定义一个对AppDelegate的引用的属性,然后让SwiftUI使用AppDelegate属性包装器注入@ UIApplicationDelegateAdaptor,如下所示:

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

答案 1 :(得分:0)

在下面的链接中找到了答案:

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

说明在链接上。