Ad

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?

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad