首页 > 解决方案 > 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)
        }
    }
}

标签: swiftgoogle-cloud-firestorefirebase-authenticationswiftui

解决方案


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
}

推荐阅读