How to get steps count on hourly basis from HealthKit Swift 4

3k views Asked by At

I need to plot graph for steps taken by user on hourly basis on any specific date. But if the user's steps start today at 3:58 pm and end today at 4:10 pm then I am getting just one HKStatistics object for this period of time. I am not able to break this data into two samples as I need to get steps taken in the 3-4 pm slot and the 4-5 pm slot.

  static func getSteps(date: Date, duration: DateComponents, completion: @escaping ([HKSample]) -> Void) {
        let quantityType : Set = [HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!]

        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
        let startOfDay = Calendar.current.startOfDay(for: date)
        if let endOfDay = Calendar.current.date(byAdding: duration, to: startOfDay) {
            var interval = DateComponents()
            interval.hour = 1
            let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: endOfDay, options: .strictStartDate)

            let query = HKSampleQuery.init(sampleType:stepsQuantityType,
                                                 predicate: predicate,
                                                 limit: HKObjectQueryNoLimit,
                                                 sortDescriptors: nil,
                                                 resultsHandler: { (query, results, error) in
                                                    guard let result = results else {

                                                                            return
                                                                        }
                                                   // print("result healthkit",result.description)
                                                    //print("Total count:",)
                                                    completion(result)
            })

            healthStore.execute(query)
        }
    }
2

There are 2 answers

0
Allan On BEST ANSWER

Don't use HKSampleQuery for charting quantity types. HKStatisticsCollectionQuery is designed for this purpose and will split samples that fall into separate regions of your chart for you. See the documentation for examples of how to build the query and use its results.

0
Rob Napier On

You're correct, you can't split the sample. That's the all the information that's available. Steps are not stored step-by-step; they're aggregated into blocks to reduce power and storage requirements (mostly power; it's easier to accumulate a value in hardware and periodically read it than to query the real time clock every single time a step is detected).

In order to do what you're discussing, you'll need to average the steps over the period. So if there were 100 steps over the period 3:58p to 4:07p, that averages 10 steps/minute, and you would allocate 20 steps to the 3p-4p block and 80 steps to the 4p-5p block. That's the best information you have.