【发布时间】:2020-01-20 10:16:52
【问题描述】:
我有这组代码,我只想运行:self.performSegue 在所有 for 循环和 Firebase 的所有异步任务都运行完之后:
getFeaturedPost(withCompletion: startNext)
func getFeaturedPost(withCompletion completion: () -> Void ) {
print("Getting featured posts...")
ref.child("featured").child("amount").observeSingleEvent(of: .value, with: { (snapshot) in
self.numberOfPosts = snapshot.value as! Int
print("There's \(self.numberOfPosts) posts avaliable.")
for pos in 0..<self.numberOfPosts{
print("Getting reference names for post: \(pos + 1)")
self.ref.child("featured").child("post\(pos + 1)").observeSingleEvent(of: .value, with: { (snapshot) in
let postID = (snapshot.value as? NSDictionary)?["postID"] as? String ?? ""
let userOfPost = (snapshot.value as? NSDictionary)?["userOfPost"] as? String ?? ""
self.customValues.append(("/users/public/\(userOfPost)/posts/\(postID)"))
})
}
})
print("Done! The posts are: \(customValues)")
completion()
}
func startNext()
{
getPostData(withCompletion: {
print("Finished getting data, going to main screen.")
self.performSegue(withIdentifier: "showHome", sender: nil)
})
}
func getPostData(withCompletion completion: () -> Void ) {
print("Getting idividual post data, there are \(customValues.count) posts")
for i in 0..<customValues.count {
print("Currently on post: \(i)")
let encodedURL = (customValues[i] + "/postURL")
ref.child(encodedURL).observe(.value, with: { (snapshot) in
if let newURL = snapshot.value as? String{
print("Sending \(newURL) to DemoSource Class")
DemoSource.shared.add(urlString: newURL)
}
})
}
completion()
}
然而startNext() 函数(转到下一个视图)在getFeaturedPost 开始之前执行,它是for 循环,它打印它当前所在的帖子。最后,当我使用DemoSource.shared.add(urlString: newURL) 将数据发送到演示源类时,newURL 为 nil,我有一个控制台日志,显示每个函数的打印语句的顺序:
Getting featured posts...
Done! The posts are: []
Getting idividual post data, there are 0 posts
Finished getting data, going to main screen. // This line should be printed last meaning this function is being executed too early
There's 2 posts avaliable.
Getting reference names for post: 1 // These two lines should be called before the line 'Finished getting data'
Getting reference names for post: 2
【问题讨论】:
-
print(Done行和completion()调用立即执行。数据库请求很晚才返回数据。在循环中使用异步任务,您需要DispatchGroup -
@vadian 我想了很多,你能指出我应该在哪里添加 dispatchGroups,因为我知道在我做两个 firebase 查询时可能不止一个地方可以添加它们。
标签: ios swift firebase firebase-realtime-database