How can my code know when Firebase finished receiving data?

I just want to ask how to retrieve data from a database. How can I process data from a database with a remote database? I do not see the completion handler. I want to call some function after the database data recovery is completed. How can I handle ???

DataService.ds.POST_REF.queryOrderedByChild("created_at").observeEventType(.ChildAdded, withBlock: { snapshot in if let postDict = snapshot.value as? Dictionary<String, AnyObject> { let postKey = snapshot.key let post = Post(postKey: postKey, dictionary: postDict) self.posts.append(post) } }) 
+7
ios9 swift firebase firebase-database
source share
3 answers

In Firebase there is no concept of "finished" (when listening to "added child"). This is just a stream of data (imagine someone adding a new record before the original data is “finished”). You can use the value event to retrieve the entire object, but this will not give you new entries, as they are added as an added child.

If you really need to use a child and get notified when it is probably completed, you can set a timer. I do not know quickly, but here is the logic.

  • Set up a child added event.
  • Set a timer to call some finishedLoading () function in 500 ms.
  • Each time the “added by child” event is triggered, destroy the timer set in the second step and create another one (that is, extend for another 500 ms).

When new data ceases to arrive, the timer will cease to expand, and finsihedLoading () will be called 500 ms later.

500 ms - this is just a number, use any costumes.

+4
source share

Write the entire code block in a function that has a completion handler like this:

 func aMethod(completion: (Bool) -> ()){ DataService.ds.POST_REF.queryOrderedByChild("created_at").observeEventType(.ChildAdded, withBlock: { snapshot in if let postDict = snapshot.value as? Dictionary<String, AnyObject> { let postKey = snapshot.key let post = Post(postKey: postKey, dictionary: postDict) self.posts.append(post) } completion(true) }) } 

Then call it somewhere like this:

 aMethod { success in guard success == true else { //Do something if some error occured while retreiving data from firebase return } //Do something if everything went well. . . . 
+2
source share

Make one request for SingleEventOfType (.Value). This will give you all the information initially with one shot, allowing you to perform any function that you want to complete when you have this data.

You can create a separate request for childAdded, and then do whatever you want when adding a new message.

0
source share

All Articles