Edmund Edmund - 4 months ago 72
Swift Question

Firebase: observing childAdded returns existing / old records?

I have a query (written in swift):

FIRDatabase.database().reference(withPath: "\(ORDERS_PATH)/\(lId)")
.observe(.childAdded, with: { firebaseSnapshot in

let orderObject = firebaseSnapshot.value as! [String: AnyObject]

let order = AppState.Order(
title: orderObject["name"] as! String,
subtitle: orderObject["item_variation_name"] as! String,
createdAt: Date(timeIntervalSince1970: TimeInterval(orderObject["created_at"] as! Int / 1000)),
name: "name",
status: AppState.Order.Status.Pending


My database looks like this:

enter image description here

I want it to just listen all NEW incoming orders. However, every time it initially loads it fetched a bunch of existing orders with it, which isn't what I want.

I do have a
(an int that represents that time e.g. 1478637444000) on each of the orders, so if there's a solution that can utilize that that works too.

Is there something wrong with my query?

Jay Jay

Observers always fire once and read in "all the data".

A .value observer reads in everything in the node at once, where as a .childAdded observer (from the docs)

This event is triggered once for each existing child and then again every time a new child is added to the specified path.

If you think about your question, what you are actually looking for is a sub-set of all of your data. This is achieved via a query.

Your query will be to observe all .childAdded events that occur after a certain timestamp. So that's what you need to do!

Craft an observe query leveraging queryStartingAtValue(the timestamp to start at) which will return all children added after that timestamp.