ios - 查询限制(到最后 :1) firebase Chat Mesenger Swift

标签 ios swift firebase firebase-realtime-database

我正在做一个聊天信使应用程序,我想在主菜单上显示最后发送的消息,如下所示:

enter image description here

我的数据库看起来像

enter image description here

在我看来确实加载了,我正在放置 getAllMsg() 函数

    override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "Private Message"
    // Do any additional setup after loading the view.
    getAllMsg()
}

但是在我的 getAllMsg() 函数中,我不确定应该如何访问每个收件人的最后一条消息。我使用了这段代码:

func getAllMsg() {
    self.users = []

    let ref = Database.database().reference().child("privateMessages")
    ref.queryLimited(toLast: 1).observeSingleEvent(of: .childAdded) { (snapshot) in
        print(snapshot)
    }
        }

我正在将所有邮件发送给我的最后一个收件人。有人知道我该怎么做吗?

最佳答案

您正在调用Database.database().reference("privateMessages").queryLimited(toLast: 1),这意味着数据库将转到/privateMessages然后得到最后一个 child 。该子项是整个用户的消息,而不仅仅是最后一条消息。

如果您想要特定用户的最后一条消息,您应该在该用户的节点开始查询:

// this code assumes there is a current user
let user = Auth.auth().currentUser
let ref = Database.database().reference("privateMessages").child(user.uid)

现在您想要查询该用户的消息,假设通过时间戳或键(也是按时间顺序排列的)。对于后者你会这样做:

ref.queryOrderedByKey().queryLimited(toLast: 1).observeSingleEvent(of: .childAdded) { (snapshot) in
    print(snapshot)
}

关于ios - 查询限制(到最后 :1) firebase Chat Mesenger Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50166058/

相关文章:

ios - 如何编辑 Firebase 数据库中的多个数据?

string - 我如何确定调用 `String.Index.advancedBy` 不会导致崩溃?

firebase - 交易中的数据为空

node.js - firebase 函数中的 "firebase serve"未运行最新更改

iphone - SQLite3 数据库未通过 NSLog 在控制台上显示条目(将数据保存到数据库有效)

ios - 如何在 Xcode 中解析 XML 页面中的图像?

ios - WKWebView 委托(delegate)问题(使用 Swift 的 Xcode 7.3)

ios - AVCaptureVideoDataOutput 中的 `kCVPixelFormatType_128RGBAFloat` 不起作用

ios - 旋转景观集合View

ios - 连接到 firebase/firestore 时出错 : Could not reach Cloud Firestore backend