Reputation: 6359
I have the following path pattern:
/ID_Company/boxes/timestamp_of_the_day/ID_box
Let's say I just started a new day and I'm offline. Right now on Firebase DB, the path /ID_Company/boxes/timestamp_of_TODAY
doesn't exist, neither in the cache.
No I add a new box to the path /ID_Company/boxes/timestamp_of_TODAY/id_box1
If I have an observer on childAdded
event, it will be triggered. But if I have an observer on value
event, nothing is triggered.
Now let say that I was online when I added the first box. So on firebase this path /ID_Company/boxes/timestamp_of_TODAY/id_box1
exists and so it does locally.
It go offline. And I add a new box on /ID_Company/boxes/timestamp_of_TODAY/id_box2
, then 'value` event is triggered and I just don't understand why.
Why is it triggered when timestamp_of_TODAY
already exists but not when it doesn't?
Thanks for your help.
EDIT:
Here is how I add a box:
guard let startingTimestamp = date.beginning(of: .day)?.timeIntervalSince1970 else { return nil }
let boxRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)").childByAutoId()
var box = box
box.id = boxRef.key
boxRef.setValue(box.toDictionary()) { error, ref in
if let error = error as? NSError {
print(error)
completion(error)
} else {
completion(nil)
}
}
And here is how I get boxes:
guard let startingTimestamp = day.beginning(of: .day)?.timeIntervalSince1970, let endingTimestamp = day.end(of: .day)?.timeIntervalSince1970 else { return nil }
let boxesRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)")
let query = boxesRef.queryOrdered(byChild: Box.Key.dateTimestamp.rawValue).queryStarting(atValue: startingTimestamp).queryEnding(atValue: endingTimestamp + 0.001)
let handle = query.observe(.value, with: { snapshot in
var boxes: [Box] = []
for child in snapshot.children {
let box = Box(snapshot: child as! FIRDataSnapshot)
if userID == nil || box.userID == userID! {
boxes.append(box)
}
}
completion(boxes.reversed())
})
Upvotes: 29
Views: 860
Reputation: 1142
Look at this document: FIRDataEventTypeValue
You can use the FIRDataEventTypeValue event to read the data at a given path, as it exists at the time of the event
Hope it can help you.
Upvotes: 1
Reputation: 13537
I am sure but please try below. Might be work for you.
guard let startingTimestamp = day.beginning(of: .day)?.timeIntervalSince1970, let endingTimestamp = day.end(of: .day)?.timeIntervalSince1970 else { return nil }
let boxesRef = dbRef.child("ID_Company").child("boxes").child("\(startingTimestamp)")
let query = boxesRef.queryOrdered(byChild: Box.Key.dateTimestamp.rawValue).queryStarting(atValue: startingTimestamp).queryEnding(atValue: endingTimestamp + 0.001)
let handle = query.observe(.ChildAdded, with: { snapshot in
var boxes: [Box] = []
for child in snapshot.children {
let box = Box(snapshot: child as! FIRDataSnapshot)
if userID == nil || box.userID == userID! {
boxes.append(box)
}
}
completion(boxes.reversed())
})
Upvotes: 0