4thSpace 4thSpace - 10 months ago 67
iOS Question

How to listen for Firebase task completion?

In this tutorial, their Firebase code is scattered through out the controller. This makes it easy to reload a tableview when Firebase returns since your

code is in the existing

ref.queryOrdered(byChild: "completed").observe(.value, with: { snapshot in
var newItems: [GroceryItem] = []

for item in snapshot.children {
let groceryItem = GroceryItem(snapshot: item as! FIRDataSnapshot)

self.items = newItems

How can the above be handled if the Firebase code is in a class? I still need the tableview to reload, but only after Firebase returns. It looks like this:


will execute but the code path will continue on while data is still being retrieved from Firebase.
will then fire and the table will be empty (because Firebase hasn't yet returned).

I guess I'm needing to replicate Firebase's observe, but expose it on the class and piggy back off the existing observe? Seems a little convoluted. Is there a better way? Maybe just block and display and animation?

Answer Source

use the completion handler to achive this. example:

func queryOrdered(completion: (_ result: [Any]) -> ()) {
    // request here
    // getting response check on error
    // set completion for returned itmes if success
    completion([1, 2, 3])

// call the function
queryOrdered { [unowned self] (arr) in

    // get returned items
    self.myitems = arr
    // reload the table on main queue
    DispatchQueue.main.async {