如何从Firebase调用自定义类函数中的数据



我有一个post类,我用它来填充来自Firebase的post数据的集合视图。
我在获得一些用户数据时遇到了麻烦,所以我尝试将观察者放在post类中。
这似乎工作得很好,但是从Firebase获取数据有一点延迟,所以它似乎在Firebase调用完成之前完成了init()函数。

这是post类:

class Post {
    var _comment1Text: String?
    var _comment1User: String?
    var _comment1Name: String?
    init(comment1Text: String, comment1User: String, comment1Name: String) {
        self._comment1Text = comment1Text
        self._comment1User = comment1User
        self._comment1Name = comment1Name
        if self._comment1User != "" {
            DataService.ds.REF_USERS.child(self._comment1User!).observeSingleEventOfType(.Value, withBlock: { userDictionary in
                let userDict = userDictionary.value as! NSDictionary
                self._comment1Name = userDict.objectForKey("username") as? String
            })
        }
        print(self._comment1Text)
        print(self._comment1Name)
    }
}

如果我在firebase调用中打印,它就可以工作。
但是,如果我在它后面打印,由于某种原因,comment1name尚未填充。

有没有办法让self。_comment1Name包含来自Firebase的数据及时填充collectionView?

DataService.ds.REF_USERS.child(self._comment1User!).observeSingleEventOfType(.Value

是一个异步调用,所以在completionBlock中访问你的print函数,你必须在completionBlock中更新你的collectionView。

 DataService.ds.REF_USERS.child(self._comment1User!).observeSingleEventOfType(.Value, withBlock: { userDictionary in
            let userDict = userDictionary.value as! NSDictionary
            self._comment1Name = userDict.objectForKey("username") as? String
                print(self._comment1Text)
                print(self._comment1Name) 
                // Update your collectionView      
        })

异步调用在不同的网络线程中加载,因此从服务器检索DB需要一些时间。

如果你正在寻找一个自定义类和你的viewController之间的通信看看我的这个答案:- https://stackoverflow.com/a/40160637/6297658

最新更新