简体   繁体   中英

Firebase observeEventType .childAdded doesn't work as promised

When I call this observe function from in my viewcontroller, the .childadded immediately returns a object that was already stored instead of has just bin added like .childadded would suspect.

func observe(callback: RiderVC){
    let ref = DBProvider.Instance.dbRef.child("rideRequests")
    ref.observe(DataEventType.childAdded) { (snapshot: DataSnapshot) in
    if let data = snapshot.value as? NSDictionary {
    let drive = cabRide(ritID: ritID, bestemming: bestemming, 
     vanafLocatie: vanaf, taxiID: taxiID, status: status)
    print(drive)
    callback.alertForARide(title: "Wilt u deze rit krijgen?", message: "Van: \(vanaf), Naar: \(bestemming)", ritID: ritID)
    }
  } 
}

When I try this function with .childchanged , I only get a alert when it is changed like it suppose to do, but when doing .chiladded , it just gets all the requests out of the database and those requests were already there.

When I add a new request, it also gives an alert. So it works, but how can I get rid of the not added and already there requests?

Does anybody know this flaw?

This is working exactly as promised. From the documentation:

Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.

That might seem weird at first, but this is generally what most developers want, as it's basically a way of asking for all data from a particular branch in the database, even if new items get added to it in the future.

If you want it to work the way you're describing, where you're only getting new items in the database after your app has started up, you'll need to do a little bit of work yourself. First, you'll want to add timestamps to the objects you're adding to the database. Then you'll want to do some kind of call where you're asking to query your database by those timestamps. It'll probably look something like this:

myDatabaseRef.queryOrdered(byChild: "myTimestamp").queryStarting(atValue: <currentTimestamp>)

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM