Retrieving data from a closing system that retrieves data from firebase

I am trying to retrieve data from Firebase and store this data outside of the closure that retrieves this data.

    var stringNames = [String] ()
    ref?.observeEventType(.Value, withBlock: { snapshot in
        var newNames: [String] = []
        for item in snapshot.children {
            if let item = item as? FIRDataSnapshot {
                let postDict = item.value as! [String: String]
                newNames.append(postDict["name"]!)
            }
        }
        stringNames = newNames
    })
    print(stringNames)

stringNames returns empty, but when I print from inside the closure, it has the correct data. Any help would be greatly appreciated, thanks!

+4
source share
1 answer

This is because when you retrieve data from Firebase, the call is asynchronous. What can you do:

Option 1 - Set the logic in the closure (like what you have, type var inside the closure).

2 - , , :

func myMethod(success:([String])->Void){

    ref?.observeEventType(.Value, withBlock: { snapshot in
        var newNames: [String] = []
        for item in snapshot.children {
            if let item = item as? FIRDataSnapshot {
                let postDict = item.value as! [String: String]
                newNames.append(postDict["name"]!)
            }
        }
        success(newNames)
    })
}

3 -

protocol MyDelegate{
     func didFetchData(data:[String])
}

class MyController : UIViewController, MyDelegate{

    func myMethod(success:([String])->Void){
        ref?.observeEventType(.Value, withBlock: { snapshot in
           var newNames: [String] = []
           for item in snapshot.children {
               if let item = item as? FIRDataSnapshot {
                   let postDict = item.value as! [String: String]
                   newNames.append(postDict["name"]!)
               }
            }
            self.didFetchData(newNames)
        })
    }

    func didFetchData(data:[String]){
        //Do what you want
    }

}
+6

All Articles