title: HealthKit: Daily Heart Rate Average
body: <p>I am trying to get the average heart rate per day from a user's device. I have the code below which prints "avgHeart" when called, but doesn't do anything else.</p>
  
  <p>I am testing it on my own phone which definitely has heart rate data and has been authorised to read heart rate data.</p>
  
  <pre><code>func fortnightAvgHeartRate() {
      print("avgHEART")
      let calendar = Calendar.current
  
      var interval = DateComponents()
      // 14-day time interval
      interval.day = 1
  
      // Set the anchor date to Monday at 3:00 a.m.
      let anchorDateTMP = calendar.date(byAdding: .day, value: -14, to: Date())!
      let anchorDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: anchorDateTMP)!
  
      guard let quantityType = HKQuantityType.quantityType(forIdentifier: .heartRate) else {
          fatalError("*** Unable to create a step count type ***")
      }
  
      // Create the query
      let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                              quantitySamplePredicate: nil,
                                              options: .discreteAverage,
                                              anchorDate: anchorDate,
                                              intervalComponents: interval)
  
      // Set the results handler
      query.initialResultsHandler = {
          query, results, error in
  
          guard let statsCollection = results else {
              // Perform proper error handling here
              fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
          }
  
          let endDate = Date()
  
          guard let startDate = calendar.date(byAdding: .day, value: -14, to: endDate) else {
              fatalError("*** Unable to calculate the start date ***")
          }
  
          // Plot the weekly step counts over the past 3 months
          statsCollection.enumerateStatistics(from: startDate, to: endDate) { [unowned self] statistics, stop in
  
              if let quantity = statistics.sumQuantity() {
                  let date = statistics.startDate
                  let value = quantity.doubleValue(for: HKUnit.count())
  
                  let formatter = DateFormatter()
                  formatter.dateFormat = "ddMMMyyyy"
                  let dateResult = formatter.string(from: date)
  
                  print("HEART")
                  self.addToArray(date: dateResult, value: value, number: 5)
              }
          }
      }
  
      HKHealthStore().execute(query)
  }
  </code></pre>
  
  <p>The called function is as follows:</p>
  
  <pre><code>var dateArray: [String] = []
  var avgHeartRateDataArray: [Double] = []
  
  func addToArray(date: String, value: Double, number: Double) {
      // ...
      if number == 5 {
          avgHeartRateDataArray.append(value)
          print("avgHeartRate: \(avgHeartRateDataArray)")
      }
  
      if dateArray.contains(date) {
          // Do nothing
      } else {
          dateArray.append(date)
      }
  
      print("ARRAY1: \(dateArray)")
  }
  </code></pre>
  
  <p>And in this, <code>print("avgHeartRate: \(avgHeartRateDataArray)")</code> is not called at all.</p>
  
  <p>Ideally I'd like the <code>avgHeartRateData</code> array to be populated with the average heart rate for the past 14 days.</p>