我正在尝试找出处理函数完成的最佳方法。

该函数从firebase调用数据,并将其添加到字典数组中。因为这是为 map 和添加注释而设计的,所以循环会在到达最终附加版本之前添加大量数据,因此其在注释中的 throw 负荷会下降。我想知道是否可以在完成时在循环上调用完成,然后调用函数ShowSightings()。

func getDatafromFB() {
    DataService.ds.REF_POSTS.child("postCodes").observeSingleEvent(of: .value, with: { (snapshot) in

        let value = snapshot.value as? NSDictionary
        let postsIds = value?.allKeys as! [String]
        for postId in postsIds {
            let refToPost = Database.database().reference(withPath: "posts/" + "postCodes/" + postId)
            refToPost.observe(.value, with: { snapshot in
                if snapshot.exists() {

                    let postDict = snapshot.value as? [String: AnyObject]

                    print("Tony: before append post \(self.posts)")
                    self.posts.append(postDict!)
                    print("Tony: post \(self.posts)")


                }else {
                    print("Tony: Couldn't get the data")
                }
            })
        }
        print("Tony: The compleetion result \(self.posts)")
    })

}

最佳答案

您可以尝试以下方法:

func doAsyncTask(completionHandler:@escaping (Bool) -> ()){
//do async tasks
completionHandler(true)  //<- call this when the data is retrieved
//so in your case, see below
}

override func viewDidLoad{
    doAsyncTask(){ succes in
    //succes gives true or false
    }
}

//your case
 }else {
  print("Tony: Couldn't get the data")
}
completionHandler(true) //<- right there

这是用于1个异步任务。我看到您要使用多个异步任务。这是调度组的工作。我将某些函数更改为采用参数。看一下这个:
func doAsyncTask(postID: String, completionHandler:@escaping (Bool) -> ()){
//do async tasks
completionHandler(true)

}

override func viewDidLoad{
var arrPostIDs = [String]()
//append to arrPostIDs here
let postIDDispatchGroup = DispatchGroup()
for postID in arrPostIDs{
postIDDispatchGroup.enter()
   doAsyncTask(postID: postID){ succes in
    //succes gives true or false
    postIDDispatchGroup.leave()
   }
  }
 postIDDispatchGroup.notify(queue: .main) {
 //everything completed :), do whatever you want
  }
}

关于ios - 在Firebase完成后向iOS,Swift中的功能添加完成功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45664499/

10-14 18:52
查看更多