swiftgrand-central-dispatchdispatchgroup

Why DispatchGroup is not working correctly


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


Solution

  • 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()
        }
    }