dwinnbrown dwinnbrown - 6 months ago 50
Swift Question

Swift - Firebase multiple snapshots

So I need to capture the contents from different paths in my firebase database and save them into an array so that I can put them into a chart.

Is there any way I can get the

snapshot.Value
and save it into a variable that can then be accessed at a later point in the code?

This is the code which shows what I'm trying to do:

override func viewDidLoad() {
super.viewDidLoad()

leave.observeEventType(.Value, withBlock: { snapshot in
let vaiable = snapshot.value
})

remain.observeEventType(.Value, withBlock: { snapshot in
let variableTwo = snapshot.value
})

undecided.observeEventType(.Value, withBlock: { snapshot in
let vaiableThree = snapshot.value
})

let options = ["Remain", "Leave", "Undecided"]
let results = [variable, variableTwo, variableThree]
setChart(options, values: results)


But I believe that the firebase calls are made last of all, meaning that the variables are empty in the 'results' array.

Anything I'm missing?

Answer

First of all, you've got an issue with 'scope'. A variable declared inside of a function or a callback will never be accessible from the outside of that function or callback.

One solution to your problem could be like this:

var results: [FIRDataSnapshot] = []
override func viewDidLoad() {
    super.viewDidLoad()

    leave.observeEventType(.Value, withBlock: { snapshot in
    self.results.append(snapshot.value)
})

remain.observeEventType(.Value, withBlock: { snapshot in
    self.results.append(snapshot.value)
})

undecided.observeEventType(.Value, withBlock: { snapshot in
    self.results.append(snapshot.value)
})

But now you don't really have a way of knowing wether or not your results array is actually populated with any data, or if the callbacks are still to complete.

A safer, although still a bit cumbersome way to do it could be to refactor your callbacks out into seperate functions, and then when your first callback completes, it calls the function for the second callback, which then call the function for the third callback and then you can do something with your data. Hope that makes sense

Comments