首页 > 解决方案 > Firebase、Cloud Firestore - SwiftUI 在视图中显示集合数据

问题描述

我有一个使用 Firebase 进行电子邮件/密码身份验证的应用程序。当用户注册时,他们使用电子邮件、密码、名字和姓氏进行注册。然后,这会在我的 Cloud Firestore 中创建一个新文档,其中用户的 uid 作为 documentID。我已经成功地工作了,但是,不起作用的是在视图中显示用户的数据。

我编写了这个 fetchProfile 函数来从 Firestore 中检索用户的数据。它将当前用户 uid 打印到控制台。

import Foundation
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore

struct UserProfile: Codable {
    var uid: String
    var firstName: String
    var lastName: String
}

class UserViewModel: ObservableObject {
    @Published var user: UserProfile = UserProfile(uid: "", firstName: "", lastName: "")
    private var db = Firestore.firestore()
    
    func createProfile(profile: UserProfile, completion: @escaping (_ profile: UserProfile?, _ error: Error?) -> Void) {
        do {
          let _ = try db.collection("users").document(profile.uid).setData(from: profile)
          completion(profile, nil)
        }
        catch let error {
          print("Error writing city to Firestore: \(error)")
          completion(nil, error)
        }
      }

      func fetchProfile(userId: String, completion: @escaping (_ profile: UserProfile?, _ error: Error?) -> Void) {
        let userId = Auth.auth().currentUser?.uid ?? ""
        db.collection("users").document(userId).addSnapshotListener { documentSnapshot, error in
            guard let document = documentSnapshot else {
                print("Error fetching document: \(error!)")
                return
            }
            guard document.data() != nil else {
                print("Document data was empty")
                return
            }
            self.user = UserProfile(uid: document.get("uid") as? String ?? "", firstName: document.get("firstName") as? String ?? "", lastName: document.get("lastName") as? String ?? "")
            let user = try? documentSnapshot?.data(as: UserProfile.self)
            print(user?.uid ?? "")
        }
    }  
}

当我尝试在我的视图中显示文本时,它出现空白。这是我的视图代码。

import SwiftUI
import Firebase
import FirebaseDatabase

struct UserProfileView: View {
   
    @EnvironmentObject var userProfile: UserViewModel

  var body: some View {
        VStack {
            Form {
                Text(userProfile.user.uid)
            }
            .navigationBarTitle("User \(userProfile.user.uid)")
        }
      } 
  }

Cloud Firestore 文档

我是 swift 新手,因此不胜感激。谢谢

标签: swiftfirebasegoogle-cloud-firestoreswiftui

解决方案


每当您有一个不是要在 Text() 中显示的字符串的基本类型时,都可以使用以下方法:

Text("\(userProfile.user.uid)")

推荐阅读