Index Out of Range when Graphing Heart Data using Date as xAxis

Hello! I am getting error Fatal error: Index out of range when trying to plot the heart rate for the past month with dates as its xAxis.

Below is the code im using. Im using the Dateformatter to convert date to string and then NSString to get an Int. This is what im guessing is causing the error

The goal is to have the xaxis be the date / time of the heart rate interval and the yaxis be the Beats per minute.

 let startDate = Calendar.current.date(byAdding: .month, value: -1, to: Date())

 let query = HKSampleQuery(sampleType: sampleType, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: [sortDescriptor]) { query, result, error in
       
      guard let samples = result as? [HKQuantitySample] else {
        return
      }
       
      for sample in samples {
        let unit = HKUnit(from: "count/min")
        let HR = sample.quantity.doubleValue(for: unit)
        
    
      let dateFormatter = DateFormatter()
      let startDate = dateFormatter.string(from: sample.startDate)
      let dateInt = (startDate as NSString).integerValue
       
        var yValues = [ChartDataEntry]()
         
        yValues.append(ChartDataEntry(x: Double(dateInt), y: HR))
         
      let set1 = LineChartDataSet(entries: yValues, label: "Test")
         
      let data = LineChartData(dataSet: set1)
         
      self.lineChartView.data = data
         
      }
    }
     
    store.execute(query)
  • How could i plot the xAxis so that it shows the date interval of the heartrate taken?

    Thanks for the help in advance!!

Add a Comment

Replies

Could you tell on which line you get the crash ?

  • The Debug navigator says :

    ` let label = axis.valueFormatter?.stringForValue(axis.entries[i], axis: axis) ?? "" Thread 1: Fatal error: Index out of range

    There are no errors showing on the code itself

Add a Comment