GarySabo
GarySabo

Reputation: 6710

How to Query for HeartRates in HealthKit to get both traditional HKQuantitySamples as well as Cumulative Quantity Samples?

My heart rate query below uses the older traditional HKSampleQuery to get heart rates, however, if an app saves Heart Rates into Apple Health as a HKCumulativeQuantitySample then my query below doesn't capture all of the heart rates inside the HKCumulativeQuantitySample. How can I query so that I capture both types of heart rate samples in Apple Health?

 class func getHeartRateSamplesFrom(workout: HKWorkout, handler: @escaping ([HKQuantitySample]?, WorkoutManagerError?) -> Void) {
        
        guard let heartRateType:HKQuantityType   = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return }
        
        //predicate
        let startDate = workout.startDate
        let endDate = workout.endDate
        
        let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
        
        //descriptor
        let sortDescriptors = [
            NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) 
        ]
        let heartRateQuery = HKSampleQuery(sampleType: heartRateType,
                                           predicate: predicate,
                                           limit: (HKObjectQueryNoLimit),
                                           sortDescriptors: sortDescriptors)
        { (query:HKSampleQuery, results:[HKSample]?, error:Error?) -> Void in
            
            guard error == nil else { print("get heart rate error"); return }
            
            guard let unwrappedResults = results as? [HKQuantitySample] else { print("get heart rate error"); return}
            handler(unwrappedResults, nil)
            
            
        }
        HealthStoreSingleton.sharedInstance.healthStore.execute(heartRateQuery)
    }

Upvotes: 0

Views: 796

Answers (1)

David Wilson
David Wilson

Reputation: 36

Just replace your usage of HKSampleQuery with HKQuantitySeriesSampleQuery. That will get you all of the values matching your predicate, regardless of whether they're part of a series.

This is usable for all quantity types, so if you're ever querying for individual values of an HKQuantityType, you'll generally want to go with this query first.

Upvotes: 1

Related Questions