如何从Firebase获取降序数据?已尝试代码返回升序求解决方法
获取Firebase Realtime Database降序数据的解决方案
嘿,我来帮你搞定这个问题!Firebase Realtime Database本身并不支持直接的降序查询,但我们有两种非常实用的方法来实现你想要的效果:
方法一:写入时存储反向排序字段(推荐)
这种方法从数据源头入手,让查询自然返回降序结果,适合需要频繁获取降序数据的场景:
- 修改数据写入逻辑:当你存储
recentlocations数据时,把用于排序的字段(比如时间戳)存为负值。举个例子,如果你用时间戳来排序,就存储-Date().timeIntervalSince1970:
// 写入数据时的代码 let negativeTimestamp = -Date().timeIntervalSince1970 let locationData = [ "latitude": 37.7749, "longitude": -122.4194, "timestamp": negativeTimestamp ] let userLocationsRef = Database.database().reference() .root.child("recentlocations") .child(Auth.auth().currentUser!.uid) userLocationsRef.childByAutoId().setValue(locationData)
- 查询升序数据即得到原降序结果:现在你只需要按这个负时间戳升序查询,返回的结果就是原时间的降序排列:
let userLocationsRef = Database.database().reference() .root.child("recentlocations") .child(Auth.auth().currentUser!.uid) // 按负时间戳升序查询 userLocationsRef.queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value) { snapshot in for childSnapshot in snapshot.children { guard let snap = childSnapshot as? DataSnapshot, let locationData = snap.value as? [String: Any] else { continue } // 这里拿到的就是按原时间降序排列的位置数据 print(locationData) } }
方法二:客户端反转查询结果
如果不想修改现有的写入逻辑,也可以先获取升序数据,然后在客户端反转数组:
let userLocationsRef = Database.database().reference() .root.child("recentlocations") .child(Auth.auth().currentUser!.uid) // 先获取升序数据 userLocationsRef.queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value) { snapshot in var locationsArray: [[String: Any]] = [] // 遍历快照组装数组 for childSnapshot in snapshot.children { guard let snap = childSnapshot as? DataSnapshot, let locationData = snap.value as? [String: Any] else { continue } locationsArray.append(locationData) } // 反转数组得到降序结果 let descendingLocations = locationsArray.reversed() // 处理降序后的数组 for location in descendingLocations { print(location) } }
补充说明
如果你的recentlocations是用childByAutoId()生成的键(这些键本身是按时间升序生成的),同样可以用上面两种方法:要么在写入时自定义反向时间键,要么获取数据后反转数组。
内容的提问来源于stack exchange,提问作者Chetan Hedamba
相关产品推荐
相关产品推荐

