我正在访问存储在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()。我试图查看此函数的版本是否具有完成处理程序,但不幸的是,它不存在。

那么有什么方法可以让我在所有数据存储后才调用此方法?

请帮忙,我需要!!!

提前致谢

最佳答案

我认为你需要做这样的事情

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

10-08 06:13
查看更多