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

iOS Swift接入Firebase实时数据库写入数据时报类型转换错误

问题原因
  • 方法调用错误:Firebase Realtime Database 的 child() 方法仅接收字符串类型的参数,作用是定位子节点的路径,你此处错误地将字典类型的用户数据传入了child()方法,参数类型不匹配触发报错。
  • 字典类型不兼容:你构造的userData字典中,id、email、name三个值均为可选类型,导致字典整体推断类型为[String : String?],Firebase 不支持直接存储可选类型的值,需要先完成解包。
修复方案

首先安全解包当前登录的用户对象,避免重复写可选链,然后将写入数据的调用从child(userData)改为setValue(userData),同时保证字典内的所有值均为非可选类型。
修复后的代码如下:

private func firebaseAuthentication(withUser user: GIDGoogleUser) {
    
  if let authentication = user.authentication {
    
    let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)

    Auth.auth().signIn(with: credential) { (_, error) in
      if let error = error {
        print(error.localizedDescription)
      } else {
        // 先安全解包currentUser,避免后续反复处理可选
        guard let currentUser = Auth.auth().currentUser else {
            self.state = .signedIn
            return
        }
        // 构造非可选类型的用户数据字典
        let userData: [String: Any] = [
            "id" : currentUser.uid,
            "email" : currentUser.email ?? "",
            "name" : currentUser.displayName ?? "",
            "photoUrl": "none",
            "premium": "false"
        ]
        
                
        ref.observeSingleEvent(of: .value) { snapshot in
            
            if !snapshot.hasChild(currentUser.uid) {
                // 用户不存在,使用setValue写入字典数据,而非child方法
                usersRef.child(currentUser.uid).setValue(userData)
            }
            
        } withCancel: { error in
            print(error.localizedDescription)
        }

        
        self.state = .signedIn
      }
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:21:04