I am trying to get the total calories burned for a workout. In the below example, deprecatedCalories
which uses sample.totalEnergyBurned
returns the correct number of calories, but it tells me that it is deprecated and I should use .statistics
to retrieve information about the workout instead. So I did that with the calories
variable.
However, sample.statistics(for: quantityType)?
returns nil, while the deprecated code returns the correct amount. As far as I can tell, there is no other quantity type I can use besides HKQuantityType(.activeEnergyBurned)
. Is this something not achievable in Swift right now with .statistics()
, or is there another way to retrieve totalEnergyBurned
per workout which is not be deprecated?
class HealthKitManager:ObservableObject {
@Published var exercises:[Exercise] = []
var healthStore: HKHealthStore
var queryAnchorExercise: HKQueryAnchor?
var queryExercise: HKAnchoredObjectQuery?
init() {
if HKHealthStore.isHealthDataAvailable() {
healthStore = HKHealthStore()
} else {
fatalError("Health data not available")
}
initExerciseQuery()
}
func initExerciseQuery() {
self.queryExercise = HKAnchoredObjectQuery(
type: HKWorkoutType.workoutType(),
predicate: healthLastDayPredicate(),
anchor: queryAnchorExercise,
limit: HKObjectQueryNoLimit,
resultsHandler: exerciseUpdateHandler
)
self.queryExercise!.updateHandler = self.exerciseUpdateHandler
healthStore.execute(self.queryExercise!)
}
func exerciseUpdateHandler(query: HKAnchoredObjectQuery, newSamples: [HKSample]?, deleteSamples: [HKDeletedObject]?, newAnchor: HKQueryAnchor?, error: Error?) {
if let error = error {
print("Health query error (error)")
} else {
if let newSamples = newSamples as? [HKWorkout], !newSamples.isEmpty {
for sample in newSamples {
let quantityType = HKQuantityType(.activeEnergyBurned)
let calories = sample.statistics(for: quantityType)?
let deprecatedCalories = sample.totalEnergyBurned?
}
}
if let anchor = newAnchor {
self.queryAnchorExercise = anchor
}
}
}
}