swift - 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)")
}
}
}
我是 swift 新手,因此不胜感激。谢谢
解决方案
每当您有一个不是要在 Text() 中显示的字符串的基本类型时,都可以使用以下方法:
Text("\(userProfile.user.uid)")
推荐阅读
- c++ - 可执行文件或 DLL 中的构建路径 (Visual Studio C++/Windows)
- asp.net-mvc - EF Core:将元素添加到集合而不检索完整对象
- asp.net-core - Ocelot - 将令牌添加到下游 URL
- python - 如何为 OneHotEncoder 创建一个 for 循环
- python - 使用两个列表中的值替换数据框中的值
- java - JDBC资源和连接池中不显示新的数据源和连接池
- azure - Azure 存储帐户无法创建新目录或删除目录
- ssl - webrtc 中的 dtls 域 args 是从哪里来的?
- sql - Postgres触发刷新物化视图一段时间后不起作用
- javascript - WebStorm 使用 Stdin 参数运行 JS 文件