swift - DocumentId 包装器无法正常工作
问题描述
我在我的数据结构中使用@DocumentId:
struct UserProfile : Codable, Identifiable {
@DocumentID var id: String? = UUID().uuidString
}
当我尝试访问 id 时,我得到一个随机的字母字符串 (04F9C67E-C4A5-4870-9C22-F52C7F543AA5) 而不是 firestore 中的文档名称 (GeG23o4GNJt5CrKEf3RS)
要访问 documentId,我在 ObservableObject 中使用以下代码:
class Authenticator: ObservableObject {
@Published var currentUser: UserProfile = UserProfile()
@Published var user: String = ""
func getCurrentUser(viewModel: UsersViewModel) -> String {
guard let userID = Auth.auth().currentUser?.uid else {
return ""
}
viewModel.users.forEach { i in
if (i.userId == userID) {
currentUser = i
}
}
print("userId \(currentUser.id ?? "no Id")")
print("name \(currentUser.name)")
return userID
}
currentUser 是一个 UserProfile 结构。currentUser.name 返回正确的值。我究竟做错了什么?
currentUser 是使用以下方法填充的数组的成员:
func fetchData() {
db.collection("Users").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents")
return
}
self.users = documents.compactMap { (queryDocumentSnapshot) -> UserProfile? in
return try? queryDocumentSnapshot.data(as: UserProfile.self)
}
}
}
解决方案
UserProfile 结构的 id 和 Firestore 中数据的 id 是分开的。这就是为什么您会看到随机的字母串。
我会改变你的结构类似于下面,你可以在初始化时忽略常规的“id”变量并引用documentID。
struct UserProfile : Codable, Identifiable {
var id = UUID() // ID for the struct
var documentID: String // ID for the post in Database
}
推荐阅读
- sql - In a Sub-Select, select Column from a Max-ID Row without ORDER BY
- node.js - Typescript "error: no pg_hba.conf entry for host "x", user "x", database "x", SSL off"
- protocol-buffers - Grpc-node: How to edit metadata in gRPC server and send back edited metadata to grpc-client?
- ios - Understanding AVCaptureDevice exposureDuration, exposureTargetOffset, exposureTargetBias
- ubuntu - cannot install "[pycharm-professional": snap not found
- go - Openshift API query with Openshift/Client-go
- flutter - Is it a good practice using Bloc and Provider in a same app?
- python - How to generate a list of string + yearly increments?
- javascript - How can I display several inputs by clicking on a button?
- azure-cognitive-search - 拥有更多不可搜索的可检索字段会降低 azure 搜索性能吗?