答案是您需要使用一些逆向逻辑,并在每个节点内存储一个时间戳键:值对作为负值。我省略了 user_id: 1 以保持答案更清晰。
这是 Firebase 结构
"test" : {
"-KFUR91fso4dEKnm3RIF" : {
"timestamp" : -1.46081635550362E12
},
"-KFUR9YH5QSCTRWEzZLr" : {
"timestamp" : -1.460816357590991E12
},
"-KFURA4H60DbQ1MbrFC1" : {
"timestamp" : -1.460816359767055E12
},
"-KFURAh15i-sWD47RFka" : {
"timestamp" : -1.460816362311195E12
},
"-KFURBHuE7Z5ZvkY9mlS" : {
"timestamp" : -1.460816364735218E12
}
}
这就是将其写入 Firebase 的方式;我只是用一个 IBAction 作为一个按钮来写出几个节点:
let testRef = self.myRootRef.childByAppendingPath("test")
let keyRef = testRef.childByAutoId()
let nodeRef = keyRef.childByAppendingPath("timestamp")
let t1 = Timestamp
nodeRef.setValue( 0 - t1) //note the negative value
以及读取它的代码
let ref = self.myRootRef.childByAppendingPath("test")
ref.queryOrderedByChild("timestamp").queryLimitedToFirst(3).observeEventType(.ChildAdded, withBlock: { snapshot in
print("The key: \(snapshot.key)") //the key
})
我声明了一个小函数来返回当前时间戳
var Timestamp: NSTimeInterval {
return NSDate().timeIntervalSince1970 * 1000
}
和输出
The key: -KFURBHuE7Z5ZvkY9mlS
The key: -KFURAh15i-sWD47RFka
The key: -KFURA4H60DbQ1MbrFC1
如您所见,它们的顺序相反。
注意事项:
- 将时间戳记为负值
- 读取时使用 .queryLimitedToFirst 而不是 last。
注意,您也可以像往常一样读取数据并将其添加到数组中,然后对数组进行降序排序。这会使客户端付出更多的努力,如果您有 10,000 个节点,则可能不是一个好的解决方案。