SwiftUI 应用生命周期 iOS14 AppDelegate 代码放在哪里?

人气:951 发布:2022-10-16 标签: ios firebase swiftui xcode12 ios14

问题描述

现在 AppDelegateSceneDelegate 从 SwiftUI 中删除了,我把过去在 SceneDelegateAppDelegate,例如 Firebase 配置?

Now that AppDelegate and SceneDelegate are removed from SwiftUI, where do I put the code that I used to have in SceneDelegate and AppDelegate, Firebase config for ex?

所以我的 AppDelegate 目前有这个代码:

So I have this code currently in my AppDelegate:

我现在应该把这个代码放在哪里?

Where should I put this code now?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    
    FirebaseConfiguration.shared.setLoggerLevel(.min)
    FirebaseApp.configure()
    return true
}

推荐答案

这里是 SwiftUI 生命周期的解决方案.使用 Xcode 12b/iOS 14 测试

Here is a solution for SwiftUI life-cycle. Tested with Xcode 12b / iOS 14

import SwiftUI
import UIKit

// no changes in your AppDelegate class
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        print(">> your code here !!")
        return true
    }
}

@main
struct Testing_SwiftUI2App: App {

    // inject into SwiftUI life-cycle via adaptor !!!
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

411