【问题标题】:Why DispatchGroup is not working correctly为什么 DispatchGroup 无法正常工作
【发布时间】:2020-05-03 15:34:35
【问题描述】:

我希望该函数先等待第一个函数从 firebase 获取数据,然后执行第二个函数,但结果发现它的工作顺序不正确

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")
    }
}

原来在MenuName之前已经打印了“完成下载”

the result image

提前谢谢你

【问题讨论】:

    标签: swift grand-central-dispatch dispatchgroup


    【解决方案1】:

    leave 行必须完成闭包内

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

    【讨论】:

      猜你喜欢
      • 2018-07-25
      • 2011-07-24
      • 2017-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2023-03-22
      相关资源
      最近更新 更多