I need to run two functions sequentially before I refresh my collection view. The first function pulls autoids from firebase and writes them into an array. The second function (getLocation) then uses that array to make another call to firebase to retrieve a value (location) beneath each autoid.
I'm using DispatchGroup() to ensure the first function finishes before the second one begins. But I also need the second function to complete before the notify refreshes the collection view.
I've written a basic for loop to test the DispatchGroup() in the second function and was able to get it to execute but I can't get it to work properly when I use it to actually fetch data from firebase.
Wondering if I may be entering and leaving in the wrong place? Here are my functions.
DispatchGroup
let dispatchGroup = DispatchGroup()
Functions:
func getLocation() {
self.dispatchGroup.enter()
for i in 0..<self.eventsArray.count {
let eventid = self.eventsArray[i]
self.ref.child("Events").child(eventid).observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let location = dictionary["location"] as! String
self.locationsArray.append(location)
} })
}
self.dispatchGroup.leave()
}
func getEvents() {
self.dispatchGroup.enter()
Database.database().reference().child("Events").observe(DataEventType.value, with: { (snapshot) in
if let dictionary = snapshot.children.allObjects as? [DataSnapshot] {
for child in dictionary {
let eventid = child.key
self.eventsArray.append(eventid)
}
self.dispatchGroup.leave()
} })
}
So I call each function then use dispatchGroup.notify.
getEvents()
getLocation()
dispatchGroup.notify(queue: .main) {
print(self.locationsArray)
self.eventsCollectionView.reloadData()
}
This is the first time I've used DispatchGroups, so any tips or recommendations are welcomed.