Difeng Chen
Difeng Chen

Reputation: 165

Swift 5, how to execute code after fetching all childadded from Firebase

How can I execute some code after fetching all childadded from Firebase in Swift 5?

I've tried using DispatchGroup and observe .value, but none of them worked efficiently.

let dispatchGroup = DispachGroup()

ref.child("path").observe(.childAdded, with: { (snapshot) in
     self.dispatchGroup.enter()
     //store snapshot data into an object
     self.dispatchGroup.leave()
})

dispatchGroup.notify(queue: .main) {
    //code to execute after all children are fetched
}

In this case, the code will be executed before fetching the data.

How can I execute code when only the callback block reaches the last child?

Upvotes: 3

Views: 908

Answers (2)

Jay
Jay

Reputation: 35657

One option is to leverage that Firebase .value functions are called after .childAdded functions.

What this means is that .childAdded will iterate over all childNodes and then after the last childNode is read, any .value functions will be called.

Suppose we want to iterate over all users in a users node, print their name and after the last user name is printed, output a message that all users were read in.

Starting with a simple structure

users
   uid_0
      name: "Jim"
   uid_1
      name: "Spock"
   uid_2
      name: "Bones"

and then the code that reads the users in, one at a time, prints their name and then outputs to console when all names have been read

var initialRead = true

func readTheUsers() {
    let usersRef = self.ref.child("users")

    usersRef.observe(.childAdded, with: { snapshot in
        let userName = snapshot.childSnapshot(forPath: "name").value as? String ?? "no name"
        print(userName)

        if self.initialRead == false {
            print("a new user was added")
        }
    })

    usersRef.observeSingleEvent(of: .value, with: { snapshot in
        print("--inital load has completed and the last user was read--")
        self.initialRead = false
    })
}

and the output

Jim
Spock
Bones
--inital load has completed and the last user was read--

Note this will leave an observer on the users node so if a new user is added it will print their name as well.

Note Note: self.ref points to my root firebase reference.

Upvotes: 5

Frank van Puffelen
Frank van Puffelen

Reputation: 599001

When you're listening to .childAdded, there is no way when your code is getting called for the last child. So if you must treat the last child different, listen for .value and loop over the children as shown here.

Upvotes: 1

Related Questions