【问题标题】:How to query items with timestamps on Firebase?如何在 Firebase 上查询带有时间戳的项目?
【发布时间】:2017-03-09 04:55:34
【问题描述】:

我想从 Firebase 节点查询活动项目。活动项目由开始日期和结束日期分隔。
这是一个结构示例:

{
    "items" : {
        "itme1" : {
            "data" : "...", //some data
            "startDate" : 12345678,
            "endDate" : 23456789
        },
        "item2" : {...}
    }
} 

日期是 Firebase 时间戳,以防止用户时移。
一个项目像这样保存在 Firebase 服务器上:

//Init data to save
var dictionary = Dictionary<String,Any>()
dictionary["data"] = "some data"
dictionary["startDate"] = FIRServerValue.timestamp()

//Save data on Firebase
let itemRef = FIRDatabase.database().reference(withPath: "items").childByAutoId()
itemRef.setValue(dictionary)

//Set end date
itemRef.observeSingleEvent(of: FIRDataEventType.value, with: { (snapshot) in
    if let dict = snapshot.value as? NSDictionary, let createdAt = dict["startDate"] as? TimeInterval {
        let startDate = Date(firebaseTimestamp: createdAt)
        let endDate = startDate.dateByAddingHours(1) //Add one hour to startDate
        itemRef.updateChildValues(["endDate":endDate.timeIntervalSince1970 * 1000])
    }
})

如何查询 Firebase 以获取 endDate &gt;= FIRServerValue.timestamp()(活动项目)所在的项目?

由于firebase时间戳FIRServerValue.timestamp()只有在Firebase上写入后才能知道,我无法直接查询FIRServerValue.timestamp()。 也许有更好的方法来设置 endDate。人们如何处理这个问题?

【问题讨论】:

  • 有什么原因不能查询 endDate startingAtValue(currentTimeStamp)?这将返回 endDate 大于 currentTime 的所有节点。也许我不完全理解这个问题?您是否总是想将当前时间戳记写为开始日期,而结束日期总是晚一小时?
  • 我可以查询 endDate startingAtValue(currentTimeStamp) 但要获得 currentTimeStamp 我需要第一次在 firebase 上保存 FIRServerValue.timestamp() 以获得当前值。这将是一个消耗资源的查询,所以也许有另一种解决方案来处理时间戳。
  • 是的,我总是想保存当前时间戳,因为开始日期和结束日期可能会有所不同(1 小时或更长时间)。

标签: swift firebase firebase-realtime-database


【解决方案1】:

你可以试试这样的。这只会查询结束日期等于或大于当前日期的项目。

let removeBeforeThisDate = NSDate()
let currentDateTimestamp = removeBeforeThisDate.timeIntervalSince1970

itemRef.queryOrderedByChild("endDate").queryStartingAtValue(currentDateTimestamp).observeEventType(.Value, withBlock: { snapshot in
...

【讨论】:

  • 我同意,但如果用户更改设备的时间,用户可以轻松修改时间戳。
  • 您可以使用 let serverTime = ServerValue.timestamp() ,您可以将其作为值传递给查询。服务器将在收到时将此解释为当前时间戳。在这里查看更多信息:stackoverflow.com/questions/25536547/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 2019-05-16
  • 2020-05-17
  • 2019-07-05
相关资源
最近更新 更多