无法根据时间戳在聊天应用程序中检索文档 [英] not able retrieve documents in chat application according to the timestamp

查看:33
本文介绍了无法根据时间戳在聊天应用程序中检索文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码根据时间戳在聊天应用程序中检索消息,但未按时间戳顺序进行检索,我应如何确保检索到的消息按时间戳顺序进行.

I am using the below code to retrieve the messages in a chat application according to the timestamp but it is not retrieving in order of the timestamp, How should I make sure that messages retrieved are in the order of the timestamp.

我正在为此应用程序使用Firestore数据库和Swift IOS

I am using Firestore database and Swift IOS for this application

下面是代码部分

时间戳保存在数据库中

    let timestamp = Int(NSDate().timeIntervalSince1970) 

用于检索邮件的代码

   let ref = Firestore.firestore().collection("messages").order(by: "timestamp", descending: true)

            ref.addSnapshotListener { (snapshot, error) in
                snapshot?.documentChanges.forEach({ (diff) in

                    let messageId = diff.document.documentID
                    let messageRef = Firestore.firestore().collection("messages")
                        .document(messageId)


                    messageRef.getDocument(completion: { (document, error) in
                        guard let dictionary = document?.data() as? [String : Any] else { return }

                        let message = Message(dictionary: dictionary)

                        print("we fetched this message \(message.text)")


                            self.messages.append(message)

                            DispatchQueue.main.async {
                                self.collectionView.reloadData()
                                let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                                self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
                            }

                    })
                })
            }

推荐答案

也许是一个疏忽,但这里发生的是代码按时间戳按降序获取所需的数据,但随后又获取了相同的数据,这些数据将无序排列因为它是异步检索的,并添加到数组中.

Perhaps an oversight but what's happening here is the code gets the data you want in descending order by timestamp, but then gets that same data again, which will be unordereed because it's being retrieved asynchronously, and adds to the array.

                   func doubleGettingData() {
                      let ref = Firestore.firestore()....
Gets data ->          ref.addSnapshotListener { (snapshot, error) in
                         snapshot?.documentChanges.forEach({ (diff) in
Gets data again ->          messageRef.getDocument(completion

要添加更多上下文,问题中显示的外部"功能实际上是按照正确的顺序获取文档.但是,由于Firebase调用是异步的,因此再次获得这些相同的文档,将以它们完成的顺序从Firebase返回它们.如果我们删除两个调用以外的所有代码,就可以证明这一点.这是一个示例Firestore结构

To add a bit more context, the 'outside' function shown in the question is in fact getting the documents in the correct order. However, getting those same documents again, they are being returned from Firebase in whatever order they complete in because Firebase calls are asynchronous. This can be proven if we remove all the code except for the two calls. Here's an example Firestore Structure

message_0:
   timestamp: 2
message_1
   timestamp: 0
message_2
   timestamp: 1

,当添加一些打印语句时,这就是发生的情况

and when some print statement are added, here's what's happening

outside func gets: message_0 //timestamp 2
outside func gets: message_2 //timestamp 1
outside func gets: message_1 //timestamp 0
   inside func returns: message_1 //timestamp 0
   inside func returns: message_2 //timestamp 1
   inside func returns: message_0 //timestamp 2

我会做一些修改...

I would make a couple of changes...

这是我的Message类和用于在其中存储消息的数组

Here's my Message class and the array to store the messages in

class Message {
    var text = ""
    var timestamp = ""
    convenience init(withSnap: QueryDocumentSnapshot) {
        self.init()
        self.text = withSnap.get("text") as? String ?? "No message"
        self.timestamp = withSnap.get("timestamp") as? String ?? "No Timestamp"
    }
}
var messages = [Message]()

,然后使用代码读取消息,并按时间戳降序并将它们存储在数组中.注意

and then the code to read the messages, descending by timestamp and store them in the array. Note

第一个查询快照包含所有现有事件的已添加事件符合查询条件的文档

The first query snapshot contains added events for all existing documents that match the query

func readMessages() {
    let ref = Firestore.firestore().collection("messages").order(by: "timestamp", descending: true)
    ref.addSnapshotListener { querySnapshot, error in
        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")
            return
        }

        snapshot.documentChanges.forEach { diff in
            if (diff.type == .added) {
                let snap = diff.document
                let aMessage = Message(withSnap: snap)
                self.messages.append(aMessage)
            }
            if (diff.type == .modified) {
                let docId = diff.document.documentID
                //update the message with this documentID in the array
            }
            if (diff.type == .removed) {
                let docId = diff.document.documentID
                //remove the message with this documentID from the array
            }
        }
    }
}

此代码还将监视消息中的更改和删除,并在事件发生时将该事件传递给您的应用.

This code will also watch for changes and deletions in messages and pass that event to your app when they occur.

这篇关于无法根据时间戳在聊天应用程序中检索文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆