我有一个帖子类,可用来用Firebase中的帖子数据填充集合视图。
我在获取一些用户数据时遇到了麻烦,因此我尝试将观察者置于post类中。
这似乎可以正常工作,但是从Firebase获取数据会稍有延迟,因此它似乎在firebase调用完成之前完成了init()函数。
这是邮政课:
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中访问您的打印功能,并且必须在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
})
异步调用加载在另一个网络线程中,因此需要一些时间才能从服务器检索数据库。
如果你正在寻找一个自定义类,并在我的这个答案你看的viewController之间的通信: - https://stackoverflow.com/a/40160637/6297658
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句