Search code examples
iosswifthealthkithksamplequery

Adding HealthKit Data into one value


I am using HealthKit to make a sample query data such as the step count. However, when I test it on my device I get a bunch of different results. Now since I have the results from different sources and different days such as [16 count, 50 count, .....]. Now I want to add up all of the data into one value. How would I achieve this? For example if I make a sample query to HealthKit, and it returns [15 count, 20 count] I want to 15 + 20 to get 35 count. How would I do that?

Here is the code that I used to query the data:

func getStepsHealthData() {
    let stepsHealthDataQuery = HKSampleQuery(sampleType: stepsHealth, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: nil) {
        (query, results, error) in

        let stepsUnit = HKUnit.countUnit()
        for result in (results as? [HKQuantitySample])! {
            stepCount = result.quantity.doubleValueForUnit(stepsUnit)
        }
    }

    healthKitStore?.executeQuery(stepsHealthDataQuery)
}

Solution

  • You can definitely do what you want with a HKSampleQuery, you just need to keep a totalSum variable and iterate over every value.

    That said there is an specific query type just for the kind of thing that you want to do called HKStatisticsQuery. According to docs:

    Statistics queries perform statistical calculations over the set of matching quantity samples

    A getTotalSteps function could be done this way:

    func getTotalSteps() {
    
        let stepsType  = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)!
        let stepsUnit  = HKUnit.countUnit()
    
        let sumOption = HKStatisticsOptions.CumulativeSum
    
        let statisticsSumQuery = HKStatisticsQuery(quantityType: stepsType, quantitySamplePredicate: nil,
            options: sumOption)
            { (query, result, error) in
                if let sumQuantity = result?.sumQuantity() {
    
                    let numberOfSteps = Int(sumQuantity.doubleValueForUnit(stepsUnit))
                    print(numberOfSteps)
                }
        }
    
        healthStore.executeQuery(statisticsSumQuery)
    }
    

    HKStatisticsOptions.CumulativeSum does the trick and the remaining code isn't too different from what you know about HKSampleQuery.

    Check it out the docs for further reading and also take a look at the HKStatistics class which provides more options to perform statistical calculations like the previous one.