0

I want the function to wait for the 1st function to get the data from the firebase first then execute the 2nd one but it turn out that it is not working in a correct order

func getMenuData(){
    getMenu()
    getIngredient()
    getRecipe()
    self.dispatchGroup.notify(queue: .main){
        print("finished download")
    }
}
func getMenu(){
    self.dispatchGroup.enter()
      let menu = self.ref.collection("menu").document("menu1")
      menu.getDocument(source: .cache) { (document, error) in
           if let document = document {
              let menuName = document.get("menuEngName") as! String
              print("MenuName = \(menuName)")

           } else {
               print("Document does not exist in cache")
           }
       }
    self.dispatchGroup.leave()
}
func getIngredient(){
    for n in 1...5 {
       print("getIngre")
    }
}
func getRecipe(){
    for n in 1...5 {
       print("getRecipe")
    }
}

It turn out that "finished download" has been print before the MenuName

the result image

thank you in advance

WPN
  • 63
  • 1
  • 5

1 Answers1

0

The leave line must be inside the completion closure

func getMenu() {
    self.dispatchGroup.enter()
    let menu = self.ref.collection("menu").document("menu1")
    menu.getDocument(source: .cache) { (document, error) in
        if let document = document {
           let menuName = document.get("menuEngName") as! String
           print("MenuName = \(menuName)")
        } else {
           print("Document does not exist in cache")
        }
        self.dispatchGroup.leave()
    }
}
vadian
  • 274,689
  • 30
  • 353
  • 361