getting data out of a closure that retrieves data from firebase
I am trying to retrieve data from Firebase and store that data outside of the closure that retrieves that 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 comes back empty, but when I print from inside the closure it has the correct data. Any help would be much appreciated, thank you!
Solution 1:
That's because when you fetch data from Firebase the call is Asynchronous. What you can do:
Option 1 - Set your logic inside the closure (Like what you have that print the var inside the closure).
Option 2 - Define your own closure that going to receive your data like:
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)
})
}
Option 3 - Use the delegate pattern
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
}
}