我正在尝试找出处理函数完成的最佳方法。
该函数从firebase调用数据并将它们添加到字典数组中。因为这是用于地图和添加注释,所以循环在添加到最终附加版本之前添加了大量数据,因此它在同一个地方抛出了大量的注释。我想知道我是否可以在完成循环时调用完成,然后调用函数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)")
})
}
答案 0 :(得分:1)
你可以试试这个:
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
}
}