使用SwiftUI从Cloud Firestore中的集合“配置文件”中获取数据。无法将类型“ [String:任何]”的值分配为类型“ UserProfile”

乔什·艾伦(Josh Allen)

我是开发新手,正在寻求帮助。

我设法创建了存储在Cloud Firestore中的配置文件的集合。我现在想检索已登录的用户个人资料信息,以在我的整个应用程序中使用。

这是我到目前为止的内容:

import SwiftUI
import Firebase

class UserViewModel: ObservableObject {
  @Published var user: UserProfile = UserProfile(uid: "", firstName: "", email: "", gender: "")
    
  private var db = Firestore.firestore()

  func fetchProfileFirstName () {
    let userId = Auth.auth().currentUser?.uid ?? "" 
    db.collection("profiles").document(userId)
      .addSnapshotListener { documentSnapshot, error in
      guard let document = documentSnapshot else {
        print("Error fetching document: \(error!)")
        return
      }
      guard let data = document.data() else {
        print("Document data was empty.")
        return
      }
      print("Current data: \(data)")
      self.user = data
    }
  }
}

我收到错误消息: 'Cannot assign value of type '[String : Any]' to type 'UserProfile'

提前致谢。

Tahmid Azam |

您的用户使用UserProfile结构,但是当您将该文档数据分配给该用户变量时,该文档数据不是以UserProfile的形式出现,而是以[String:Any]的形式出现。

您所要做的就是将[String:Any]转换为UserProfile:

更换

self.user = data

self.user = UserProfile(uid: document.get("uid") as? String ?? "", firstName: document.get("first name") as? String ?? "", email: document.get("email") as? String ?? "", gender: document.get("gender") as? String ?? "")

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档