extract detailed heart rate of a workout

I want to access the most detailled list of heartrate for a workout (from 5:26PM to 5:58PM). On iOS 13, it sounds easy with the code that print 385 heartrates:


if #available(iOS 13.0, *) {
     var index = 1
     let quantityType = HKQuantityType.quantityType(forIdentifier: .heartRate)!
     let predicate = HKQuery.predicateForSamples(withStart: self.workout.startDate, end: self.workout.endDate, options: [.strictStartDate])
     let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
     let query2 = HKQuantitySeriesSampleQuery(quantityType: quantityType, predicate: predicate) {
          (query, quantity, dateInterval, sample, done, error) in
                   
          let rate = quantity!.doubleValue(for: heartRateUnit)
          print("#\(index) \(rate)")
          index += 1        
      }
               
     HealthKitManager.shared.healthStore.execute(query2)
}

But on iOS 12 and lower, with the followig code, I've got only 4 samples :

  • 2019-02-06 4:26:32 PM +0000 to 2019-02-06 4:26:32 PM +0000 : 138.03914270987403
  • 2019-02-06 4:36:27 PM +0000 to 2019-02-06 4:36:27 PM +0000 : 168.30417943409182
  • 2019-02-06 4:46:33 PM +0000 to 2019-02-06 4:46:33 PM +0000 : 177.63391439737114
  • 2019-02-06 4:56:25 PM +0000 to 2019-02-06 4:56:25 PM +0000 : 167.2611138237847


let heartRateQuery = HKSampleQuery(
     sampleType: HKQuantityType.quantityType(forIdentifier: .heartRate)!,
     predicate: HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.strictStartDate]),
     limit: HKObjectQueryNoLimit,
     sortDescriptors: [ NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true) ]) { (_: HKSampleQuery, results: [HKSample]?, error: Error?) in
                           
     let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
                  
     for result in results! {
          if let sample:HKQuantitySample = result as? HKQuantitySample {
               let rate = sample.quantity.doubleValue(for: heartRateUnit)     
               print("\(sample.startDate) to \(sample.startDate) : \(rate)")          
          }
     }

How can I get more samples with iOS < 13 ? What do I miss ?

Replies

Do someone can confirm at least that before iOS 13 we can extract heart rate samples from HealkthKit ?

You're using two different types of queries.


The HKQuantitySeriesSampleQuery that is available iOS 13+ will give you different results than just the simple HKSampleQuery.


1. Is the HeartRate data you are expecting to have returned recorded by your app?

2. Does the Health app on the iOS 12 device show many more samples than what you're getting in your query?


From your samples provided from iOS 12, looks like the recordings are every 10 minutes. This could be the standard recording from the watch, I can't remember if it was every 6, 8, or 10 minutes that samples would be recroded (when not in an active workout).