我在我的应用中使用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中显示任何内容。
答案 0 :(得分:1)
您的代码结构不正确。您有一个对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)
}
})
}
}
})
}