How to read data from iOS HealthKit minute by minute using Swift

406 views Asked by At

I'm correctly reading step data from HealthKit hourly, daily, weekly, etc. But when it comes to reducing the query time interval to less than 15 minutes, HealthKit returns wrong step data. I need to read data minute by minute. Is it possible?

Here is my code. HealthKit returning data by using the code below, but it shows step data more than 10 percent.

    func getMinutelyStepData(startingDate: Date) {

    print("Setting hourly step data for \(startingDate)")
    var loopCount = 0
    var totalStep = 0.0
    let endOfDay = startingDate.endOfDay//Calendar.current.date(byAdding: .hour, value: 23, to: startingDate)!
    let stepType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!

    let minutely = DateComponents(minute: 1)

    var queryStepMinutely: HKStatisticsCollectionQuery?
    let predicate = HKQuery.predicateForSamples(withStart: startingDate, end: endOfDay, options: .strictStartDate)
    let myAnchorDate = Calendar.current.date(bySettingHour: 0, minute: 0, second: 0, of: Date())!
    
    queryStepMinutely = HKStatisticsCollectionQuery(quantityType: stepType, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: myAnchorDate, intervalComponents: minutely)
    
    queryStepMinutely!.initialResultsHandler = { query, statisticsCollection, error in
        
        if let result = statisticsCollection {
            result.enumerateStatistics(from: startingDate, to: endOfDay) { (statistics, stop) in

                if let step = statistics.sumQuantity() {
                    let value = step.doubleValue(for: .count())
                    totalStep += value
                    print("Minutely step data: \(value), \(statistics.startDate), my total step: \(totalStep)")
                } else {
                    print("No step data for minutely available, so add 0..., \(statistics.startDate), \(statistics.endDate)")
                }
            }

        }
        
    }
    myHealthStore.execute(queryStepMinutely!)
}
0

There are 0 answers