Search code examples
iosswifthealthkit

Get calories burned overnight from Health Kit


I use this function to get calories burned from Health Kit after syncing with RunKeeper

func getActiveEnergy(currentDate: Date ,completion: @escaping ((_ totalEnergy: Double) -> Void)) {
    let calendar = Calendar.current
    var totalBurnedEnergy = Double()
    let startOfDay = Int((currentDate.timeIntervalSince1970/86400)+1)*86400
    let startOfDayDate = Date(timeIntervalSince1970: Double(startOfDay))
    //   Get the start of the day
    let newDate = calendar.startOfDay(for: startOfDayDate)
    let startDate: Date = calendar.date(byAdding: Calendar.Component.day, value: -1, to: newDate)!

    //  Set the Predicates
    let predicate = HKQuery.predicateForSamples(withStart: startDate as Date, end: newDate as Date, options: .strictStartDate)

    //  Perform the Query
    let energySampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)

    let query = HKSampleQuery(sampleType: energySampleType!, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
        (query, results, error) in
        if results == nil {
            print("There was an error running the query: \(error)")
        }

        DispatchQueue.main.async {

            for activity in results as! [HKQuantitySample]
            {
                let calories = activity.quantity.doubleValue(for: HKUnit.kilocalorie())
                totalBurnedEnergy = totalBurnedEnergy + calories
            }
            completion(totalBurnedEnergy)
        }
    })
    self.healthStore.execute(query)
}

The problem is if I use RunKeeper to collect data overnight, I can't get separated values each day. Example:

enter image description here

Apr 17: 3.1 Apr 18: 4.2

But inside my app, I only get the data below: Apr 17: 7.3

Apr 17 in Health app:

enter image description here

any ideas?


Solution

  • sovlved the problem with the link below: https://developer.apple.com/reference/healthkit/hkstatisticscollectionquery