Reputation: 301
I need this array
self.values.append(value)
in order to append another array with the values from the array above^. Pretty much i need to pass one array to another function with the appended values.
func updateChartValues() -> (LineChartDataSet) {
self.recieveChartValues()
var entries: [ChartDataEntry] = Array()
for i in 0 ..< values.count {
entries.append(ChartDataEntry(x: Double(i), y: Double(values[i]), data: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil)))
How can I get these values that are appended from recieveChartValues() to updateChartValues? The main confusion is because they are appended from Firebase.
func recieveChartValues() {
//Firebase Initialization
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snap) in
print("error3")
if let snaps = snap.value as? [Any]{
for val in snaps {
if let value = val as? Int{
self.values.append(value)
//print(self.values)
}
}
}
})
}//retrive values func
func updateChartValues() -> (LineChartDataSet) {
self.recieveChartValues()
var entries: [ChartDataEntry] = Array()
for i in 0 ..< values.count {
entries.append(ChartDataEntry(x: Double(i), y: Double(values[i]), data: UIImage(named: "icon", in: Bundle(for: self.classForCoder), compatibleWith: nil)))
print("Enetrie ", entries)
}
self.dataSet = LineChartDataSet(values: entries, label: "Bullish vs. Bearish")
self.dataSet.mode = LineChartDataSet.Mode.cubicBezier
return dataSet
}
Upvotes: 1
Views: 1102
Reputation: 1227
Like Paulw11 says, the crux is the asynchronous nature. If you just do
recieveChartValues()
updateChartValues()
recieveChartValues()
runs (and returns immediately), then updateChartValues()
runs (using self.values
without the new value being appended), then the completion closure that appends the new value runs.
Either directly call updateChartValues()
in the completion closure, like this:
ref.child("general_room_index").observeSingleEvent(of: .value, with: {(snap) in
...
if let snaps = snap.value as? [Any] {
for val in snaps {
if let value = val as? Int{
self.values.append(value)
updateChartValues()
}
}
}
})
Or add a closure parameter to recieveChartValues()
and call that when you get a new value:
func recieveChartValues(_ completion: @escaping () -> Void) {
...
if let snaps = snap.value as? [Any] {
for val in snaps {
if let value = val as? Int{
self.values.append(value)
completion()
}
}
}
}
And call recieveChartValues
like this:
recieveChartValues { self.updateChartValues() }
You can also add a parameter to the completion closure so you can pass the received value to it, if you are interested in that:
func recieveChartValues(_ completion: @escaping (Int) -> Void) {
...
if let value = val as? Int{
self.values.append(value)
completion(value)
}
...
}
Then your closure will be called with the new value:
recieveChartValues { newValue in
print("Received \(newValue)")
self.updateChartValues()
}
Upvotes: 1