【问题标题】:Get data from firestore and assign it to an array of dictionaries从 firestore 获取数据并将其分配给字典数组
【发布时间】:2021-08-17 11:15:24
【问题描述】:

我正在尝试从 firestore 集合中获取数据并将其分配给字典数组。对于下面的这部分代码......我收到错误“从'QuerySnapshot投射?'到不相关的类型 '[[String : Any]]' 总是失败”并且控制台打印“不工作”。

guard let snap = snapshot as? [[String:Any]] else {
                print("is not working")
                completion(.failure(DatabaseError.failedToFetch))
                return
            }

这是完整的代码。

 // fetches and returns all conversations for the user with passed in uid
public func getAllConversations(for uid: String, completion: @escaping(Result<[Conversation], Error>) -> Void) {
    
    print("fetching all convos")
    
    //NEW
    let db = Firestore.firestore()
    let CurrentUser = Auth.auth().currentUser?.uid
    let ListRef = db.collection("users").document(CurrentUser!).collection("conversations")
    
    // fetch the current users convo list
    ListRef.getDocuments { snapshot, error in
        if let err = error {
            debugPrint("Error fetching documents: \(err)")
        } else {
            guard let snap = snapshot as? [[String:Any]] else {
                print("is not working")
                completion(.failure(DatabaseError.failedToFetch))
                return
            }
            print("is working")
            let conversations: [Conversation] = snap.compactMap({ dictionary in
                guard let id = dictionary["id"] as? String,
                      let name = dictionary["name"] as? String,
                      let otherUserUID = dictionary["other_user-uid"] as? String,
                      let latestMessage = dictionary["latest-message"] as? [String:Any],
                      let date = latestMessage["date"] as? String,
                      let message = latestMessage["message"] as? String,
                      let isRead = latestMessage["is-read"] as? Bool else {
                    return nil
                }
                
                //save other user ID to a global var
                self.test = otherUserUID
                
                //assign data into an array of dictionaries
                let latestConvoObject = LatestMessage(date: date, text: message, isRead: isRead)
                
                return Conversation(id: id, name: name, otherUserUid: otherUserUID, latestMessage: latestConvoObject)
                
            })
            completion(.success(conversations))
        }
    }
} 

【问题讨论】:

  • 嗨 Mikhail,不,现在是从 firestore 获取数据,但是我如何将获取数据分配给字典数组?
  • for doc in (snapshot?.documents)! {}
  • 我可以从 firestore 获取数据作为字典,但现在我想将该字典分配给数组,这可能吗?
  • 有很多方法可以做到这一点,但有两个重要问题。 1) 为什么是字典数组? 2)问题中的代码似乎是一个对话数组,而不是字典。你能澄清一下吗?哦 - 作为旁注,在编程中,大写对象通常保留给结构和类,所以不要这样做let ListRef = db.collection - 它应该是listRef

标签: swift firebase google-cloud-firestore


【解决方案1】:

有多种方法可以读取该数据,并且可以通过conforming objects to the codable protocol 简化该过程,但让我提供一个简单的示例。我不知道你的 Conversation 对象是什么样的,所以这是我的

class ConversationClass {
    var from = ""
    var to = ""
    var msg = ""
    var timestamp = 0

    convenience init(withDoc: DocumentSnapshot) {
        self.init()
        self.from = withDoc.get("from") as? String ?? "no from"
        self.to = withDoc.get("to") as? String ?? "no to"
        self.msg = withDoc.get("msg") as? String ?? "no msg"
        self.timestamp = withDoc.get("timestamp") as? Int ?? 0
    }
}

然后是从集合中读取所有对话文档的代码,将每个对话文档存储在 ConversationClass 对象中,将它们放入数组中并通过转义完成处理程序返回它

func getConversations(completion: @escaping( [ConversationClass] ) -> Void) {
    let conversationCollection = self.db.collection("conversations")
    conversationCollection.getDocuments(completion: { snapshot, error in
        if let err = error {
            print(err.localizedDescription)
            return
        }

        guard let docs = snapshot?.documents else { return }
        var convoArray = [ConversationClass]()

        for doc in docs {
            let convo = ConversationClass(withDoc: doc)
            convoArray.append(convo)
        }

        completion(convoArray)
    })
}

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2017-11-29
    • 2020-03-06
    • 2018-08-10
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    相关资源
    最近更新 更多