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

使用Firebase Auth导致SwiftUI预览崩溃,求解决方案

问题描述

用Firebase Auth检查currentUser登录状态时,Xcode预览持续崩溃,试过清理构建、重启Xcode都没用。以下是相关代码和报错截图:

ContentView代码

import SwiftUI
import SwiftfulRouting
import FirebaseAuth

struct ContentView: View {
   // @StateObject var viewModel: Router

    var body: some View {
        if AuthService.shared.isLogin() {
            TabPage()
        }
        else{
            InitPage()
        }
    }
}

AuthService代码

import Foundation
import FirebaseAuth

@MainActor
class AuthService{
    static let shared = AuthService()
    
    func login(withEmail: String, password: String) async throws{
        print("Enter")
    }
    
    func createUser(withEmail email :String, password: String, reenteredPassword:String, username:String) async throws{
        do{
            let result = try await Auth.auth().createUser(withEmail: email , password: password)
            print(result)
        }catch{
            print(error.localizedDescription)
        }
    }
    
    func isLogin() -> Bool{
        do{
            if Auth.auth().currentUser != nil {
                print("Auth here")
                return true
            }
            
            print("Log in")
            return false
        }
        catch{
            print(error.localizedDescription)
        }
    }
}

Firebase配置代码

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

@main
struct MealMeApp: App {  
    @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

报错截图

Xcode预览崩溃报错


解决办法

1. 修复isLogin()方法的逻辑错误

Auth.auth().currentUser的访问不会抛出异常,你加的do-catch块完全多余,而且catch块后没有返回值,会触发编译警告,这大概率是崩溃的原因之一。修改后的方法:

func isLogin() -> Bool {
    let loggedIn = Auth.auth().currentUser != nil
    print(loggedIn ? "已登录" : "未登录")
    return loggedIn
}

2. 给预览环境单独初始化Firebase

Xcode预览时,AppDelegate的初始化逻辑可能不执行,导致Firebase还没配置就调用Auth接口。给ContentView添加预览提供者,手动初始化Firebase:

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        FirebaseApp.configure()
        ContentView()
    }
}

3. 检查Firebase配置文件

确认GoogleService-Info.plist已经正确添加到项目中,并且勾选了对应的目标。如果文件缺失或配置错了,Firebase初始化失败,Auth调用必然崩溃。

4. 修正异步方法的错误处理(可选)

你的createUser方法用了async throws声明,但内部已经用do-catch捕获了异常,这会导致调用方的错误处理逻辑混乱。如果要在内部处理错误,直接移除方法的throws:

func createUser(withEmail email :String, password: String, reenteredPassword:String, username:String) async {
    do{
        let result = try await Auth.auth().createUser(withEmail: email , password: password)
        print(result)
    }catch{
        print(error.localizedDescription)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 03:15:21