Reputation: 522
I have a post class that I use to fill a collection view with post data from Firebase.
I was having trouble getting some user data so I tried putting the observer in the post class.
This seems to work fine, however there is a slight delay in getting the data from Firebase so it seems to finish the init() function before the firebase call is complete.
This is the post class :
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)
}
}
If I print within the firebase call, it works.
However, if I print after it, for some reason, comment1name is not yet filled.
Is there a way to get self._comment1Name to contain the data from Firebase in time to fill the collectionView?
Thanks in advance.
Upvotes: 0
Views: 436
Reputation: 9945
DataService.ds.REF_USERS.child(self._comment1User!).observeSingleEventOfType(.Value
is an Asynchronous call, So access your print functions inside the completionBlock and you have to update your collectionView inside the completionBlock.
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
})
Asynchronous call's are loaded in a different network thread, so it takes some time to retrieve the DB from the server.
If you are looking for communicating between a custom class and you viewController look at my this answer :- https://stackoverflow.com/a/40160637/6297658
Upvotes: 2