在没有AppDelegate和SceneDelegate的新SwiftUI App生命周期中,哪里可以在我的iOS应用中配置Firebase?
我已经有了一个可以使用SwiftUI完全构建的应用程序. 我当时使用Firebase使用Cloud Functions进行身份验证和通知.
I have an app already that I was able to build completely with SwiftUI. I was using Firebase for authentication and notifications using Cloud Functions.
现在有了新的SwiftUI App-> Scene->视图构造,我无法将设置添加到我的应用中.
Now with the new SwiftUI App->Scene->View construct, I am unable to add the setup to my app.
例如->最初的FirebaseApp.configure()
最初会放在AppDelegate
的didFinishLaunchingWithOptions
中,现在我不知道在何处添加此配置.
For example -> The initial FirebaseApp.configure()
would initially go in didFinishLaunchingWithOptions
in AppDelegate
, now I am at a loss of where to add this configuration.
设置远程通知也是如此.
Same goes with setting up remote notifications.
PS:如果需要先前应用程序的更多详细信息/代码,请发表评论.我没有添加任何代码,因为我觉得这是不必要的.
PS: Please comment if more details/code of the previous app is required. I did not add any code, cause I felt it was unnecessary.
在新的SwiftUI生命周期中,可以使用三种方法来初始化第三方框架:
There are three approaches for initialising third part frameworks in the new SwiftUI life cycle:
您仍然可以使用旧的生命周期模型:
You can still use the old life cycle model:
在创建新的SwiftUI项目时,您可以选择旧的生命周期模型.像以前一样,这将创建一个AppDelegate
和SceneDelegate
.我承认,不像一直使用SwiftUI那样花哨-但这绝对是最简单,最直接的方法.
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.
如果要使用新的生命周期模型,请使用以下方法之一.
If you want to use the new life cycle model, use either one of the following approaches.
您可以覆盖App
类的默认初始化程序,如下所示:
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()
}
}
}
选项3:使用@ UIApplicationDelegateAdaptor
在您的App
类中,定义一个保存对AppDelegate
的引用的属性,然后让SwiftUI使用@ UIApplicationDelegateAdaptor
属性包装器注入AppDelegate
,如下所示:
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
}
}