You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI iOS项目集成Firebase无AppDelegate.swift无法添加配置代码如何解决

解决SwiftUI项目无AppDelegate时的Firebase配置方案

以下操作默认你已经完成Firebase SDK的导入(通过Swift Package Manager或CocoaPods),且已经把GoogleService-Info.plist文件正确拖入项目根目录

你可以任选以下两种方案之一实现配置,不需要同时使用:

方案1:直接在App入口初始化(最简单,适合新手)

  • 找到项目中带@main标记的Swift文件,默认命名规则为「你的项目名+App.swift」,例如项目名为MyTodo,文件名为MyTodoApp.swift
  • 在该文件中添加初始化方法调用Firebase配置即可,完整代码示例如下:
import SwiftUI
import Firebase

@main
struct 替换为你的项目名App: App {
    // 新增初始化方法
    init() {
        FirebaseApp.configure()
    }
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

方案2:自定义AppDelegate(适合后续需要使用AppDelegate相关能力的场景,例如推送配置)

  1. 右键项目根目录,选择「New File」,新建一个Swift文件,命名为AppDelegate.swift
  2. 在AppDelegate.swift中写入以下代码:
import UIKit
import Firebase

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        FirebaseApp.configure()
        return true
    }
}
  1. 回到带@main标记的App入口文件,绑定自定义的AppDelegate,完整代码示例如下:
import SwiftUI

@main
struct 替换为你的项目名App: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

注意事项

  • 不要同时在两种方案中调用FirebaseApp.configure(),重复初始化会导致运行报错
  • 代码中的「替换为你的项目名App」要和你原有文件中的结构体名保持完全一致,不要写错

内容的提问来源于stack exchange,提问作者Nekicode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 13:54:04