Reputation: 964
I want to query active items from a Firebase node. An active item is delimited by a start date and an end.
Here is a sample of the structure :
{
"items" : {
"itme1" : {
"data" : "...", //some data
"startDate" : 12345678,
"endDate" : 23456789
},
"item2" : {...}
}
}
Dates are Firebase timestamps to prevent user time shifting.
An item is saved on Firebase server like this:
//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])
}
})
How can I query Firebase to get items where endDate >= FIRServerValue.timestamp()
(active items) ?
As firebase timestamp FIRServerValue.timestamp()
can only be known only after it has been written on Firebase, I cannot query FIRServerValue.timestamp()
directly.
Maybe there is a better way to set endDate. How do people handle this?
Upvotes: 1
Views: 2607
Reputation: 1620
You could try something like this. This would only query items where the end date equals the current date or greater.
let removeBeforeThisDate = NSDate()
let currentDateTimestamp = removeBeforeThisDate.timeIntervalSince1970
itemRef.queryOrderedByChild("endDate").queryStartingAtValue(currentDateTimestamp).observeEventType(.Value, withBlock: { snapshot in
...
Upvotes: 1