无法加载图表数据

Can't load data for Charts

我正在为我的应用程序使用图表框架。如果我给它一些静态数据,我可以很容易地将值放入图表中。但是当我尝试从 Firebase 获取数据时,似乎在数据获取完成之前调用了 setChart 函数。

有什么建议吗?正在从 ViewDidLoad()

调用我的 GetLogs() 函数
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: {[=10=].date > .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: {[=10=].date > .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)
          }
          
        })
      }
    }
  })
}