Katie
Katie

Reputation: 21

How do I retrieve only the autoids since I last called a function from firebase using swift.

My firebase database is structured as:

events
  autoid
    event name: "" 
    event date: "" 
  autoid
    event name: "" 
    event date: "" 

I currently have a function that returns all of the autoids from the events node then writes them to an array so I can use them in another snapshot.

The first time the function runs, it works as expected. But if I leave the view and come back it crashes. Which I think is because it's trying to append the array again, duplicating the values.

Here's my function

func getEvents() {

        self.dispatchGroup.enter()
      Database.database().reference().child("Events").observe(DataEventType.value, with: { (snapshot) in
            if let dictionary = snapshot.children.allObjects as? [DataSnapshot] {
              //  self.dispatchGroup.enter()
                for child in dictionary {
                    let eventid = child.key
                    self.eventsArray.append(eventid)
                   // print(eventid)
                    //                    print(self.eventsArray)


                }
                self.dispatchGroup.leave()
                print(self.eventsArray)

            }

        })
    }

Wondering how I can retrieve the existing autoids and any new ones that have been added when I return to the view. I tried .childadded but it returns event name, event date etc and I need the autoid.

I'm new to firebase and swift so any tips or recommendations are welcomed!

Upvotes: 0

Views: 133

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600110

If you want to first handle the initial data and then get notified of only the new data, you're typically looking for the .childAdded event.

Database.database().reference().child("Events").observe(DataEventType.childAdded, with: { (snapshot) in
    let eventid = snapshot.key
    print(eventid)
    self.eventsArray.append(eventid)
    self.dispatchGroup.leave()
    print(self.eventsArray)
}

When you first run this code, the .childAdded event fires for each existing child node. And after that, it fires whenever a new child is added. Similarly, you can listen for .childChanged and .childRemoved events to handle those.

Upvotes: 1

Related Questions