我正在为我的应用程序使用Charts框架。如果我给它一些静态数据,我可以轻松地将值放入图表中。但是,当我尝试从Firebase提取数据时,似乎在完成数据提取之前已调用setChart函数。
有什么建议么?我的GetLogs()函数正在从ViewDidLoad()调用
var dates = [String]()
var values = [Double]()
func getLogs() {
DataService.ds.REF_PERIODS.child(period.periodId).child("logs").observeSingleEvent(of: .value, with: {(userSnap) in
if let SnapDict = userSnap.value as? [String:AnyObject]{
//Run through all the logs
for each in SnapDict {
DataService.ds.REF_LOGS.child(each.key).observeSingleEvent(of: .value , with : {(Snap) in
let postData = Snap.value as! Dictionary<String, AnyObject>
let log = Log(logId: each.key, postData: postData)
self.logs.append(log)
//Add the date to the the dates and values
self.dates.append(log.date)
self.values.append(Double(log.measurement)!)
//Sorts the logs by date
self.logs.sort(by: {$0.date > $1.date})
self.tableView.reloadData()
})
}
}
//Set the charts with the given information
self.setChart(dataPoints: self.dates, values: self.values)
})
}
但是目前Firebase无法显示任何内容。
您的代码结构不正确。您有一个外部异步调用FireBase。在该异步调用中,您有一个for循环,用于对响应字典中的每个项目执行另一个异步调用。但是,您尝试在内部异步调用完成之前设置图表,这将不起作用。
由于您要在for循环中生成一大堆异步调用,因此您需要逻辑来跟踪完成了多少内部调用,并且仅在最后一个加载完成后才更新图表。像这样的东西:
var dates = [String]()
var values = [Double]()
func getLogs() {
DataService.ds.REF_PERIODS.child(period.periodId).child("logs").observeSingleEvent(of: .value, with: {(userSnap) in
if let SnapDict = userSnap.value as? [String:AnyObject]{
var completedCount = 0 //Keep track of how many items has been completed.
//Run through all the logs
for each in SnapDict {
DataService.ds.REF_LOGS.child(each.key).observeSingleEvent(of: .value , with : {(Snap) in
let postData = Snap.value as! Dictionary<String, AnyObject>
let log = Log(logId: each.key, postData: postData)
self.logs.append(log)
//Add the date to the the dates and values
self.dates.append(log.date)
self.values.append(Double(log.measurement)!)
//Sorts the logs by date
self.logs.sort(by: {$0.date > $1.date})
completedCount += 1
if completedCount == snapDict.count {
self.tableView.reloadData()
//Set the charts with the given information
self.setChart(dataPoints: self.dates, values: self.values)
}
})
}
}
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句