我正在访问存储在Firebase实时数据库中的数据,但是在访问数据之后,我想调用一个将建立视图的方法。
func fetchPostData(){
Database.database().reference().child("Posts").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: Any]{
let post = Posts()
if let val = dictionary["name"] as? String{
post.objName = val
}
if let val = dictionary["price"] as? String{
post.objPrice = val
}
if let val = dictionary["summary"] as? String{
post.objSummary = val
}
if let val = dictionary["username"] as? String{
post.postUsername = val
}
self.posts.append(post)
}
setUpView()
}, withCancel: nil)
}
问题是,与所有firebase API一样,它是异步的,因此该方法将在调用后立即返回。但是我想要做的是在所有数据都已处理并存储之后,只调用一次setUpView()
。我试图查看此函数的版本是否具有完成处理程序,但不幸的是,它不存在。
那么有什么方法可以让我在存储完所有数据之后仅调用一次此方法?
请帮助,我需要它!
预先感谢
答案 0 :(得分:0)
我认为您需要这样做
func fetchPostData(success:@escaping (Bool) -> Void){
Database.database().reference().child("Posts").observe(.childAdded, with: {(snapshot) in
if let dictionary = snapshot.value as? [String: Any]{
/// Let get posts First
let post = Posts()
if let val = dictionary["name"] as? String{
post.objName = val
}
if let val = dictionary["price"] as? String{
post.objPrice = val
}
if let val = dictionary["summary"] as? String{
post.objSummary = val
}
if let val = dictionary["username"] as? String{
post.postUsername = val
}
/// Post Retrieved and added in array
self.posts.append(post)
/// Return this function when you are sure data is retrieved from DB
success(true)
}
}, withCancel: nil)
}
用法
fetchPostData { (success) in
if success {
/// You did received bool as yes
/// Perform required Task
setUpView()
}
}