Health Kit: How to set 'totalEnergyBurned' for workout?

823 Views Asked by At

Today I worked for the first time with Apple Health Kit and successfully saved a workout in Health with the basic informations (activityType, start and end).

My app is in basic function an interval timer where you can create your own workout. Now in the next step I want to add the calories burned in the workout. This information is stored in the attribute 'totalEnergyBurned'.

Do I need to calculate this value myself or can I query this value directly if the user is wearing an Apple Watch? Or maybe the value is even automatically added to the workout if there is the corresponding record? (So far I have only tested the app in the simulator, which is why I can't answer this possibility).

My current code:

func saveToHealthKit(entryID: String) {
    if HKHealthStore.isHealthDataAvailable() {
        let healthStore = HKHealthStore()

        if (healthStore.authorizationStatus(for: HKObjectType.workoutType()) == .sharingAuthorized && healthStore.authorizationStatus(for: HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)!) == .sharingAuthorized) {
            let newWorkout = HKWorkout(activityType: HKWorkoutActivityType.highIntensityIntervalTraining, start: entry.date!, end: Date())

            healthStore.save(newWorkout) { success, error in
                guard success else {
                    // Perform proper error handling here.
                    return
                }

                // Add detail samples here.
            }
        }
    }
}
2

There are 2 best solutions below

0
On

I am not sure I understood your case correctly, but if the user is using an Apple Watch and does a workout you can query HealthKit for an HKWorkout object, which holds a totalEnergyBurned attribute.

If you are not querying this HKWorkout object, then I believe you can query for the activeEnergyBurned quantity type using the start and end date-time of the user workout in the predicate.

0
On

You need to follow the below code snippet to add total calories information to your workout

// create quantity type
let quantityType = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)!

//create unit
let unit = HKUnit.kilocalorie()

//create the quantity of total calories       
let quantity = HKQuantity(unit: unit, doubleValue: totalEnergyBurned)
        
//create a sample from the above data
let sample = HKCumulativeQuantitySample(type: quantityType,
                                        quantity: quantity,
                                        start: startDate,
                                        end: endDate)

//add the sample to your workout builder (HKWorkoutBuilder)
builder.add([sample], completion: { success, error in
            
})