Reputation: 2645
I'm working on a method that reads the active energy (kcal) from health kit but I have a problem getting the double value from the HKQuantity. My code looks like this:
func getActiveEnergy () {
let endDate = NSDate()
let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.Month, value: -1, toDate: endDate, options: [])
let energySampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierActiveEnergyBurned)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
print ("start date: ", startDate)
print ("end date: ", endDate)
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)")
}
dispatch_async(dispatch_get_main_queue()) {
for activity in results as! [HKQuantitySample]
{
self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.countUnit())
print(">>>>>", self.todayActiveEnergy)
}
}
})
self.healthKitStore.executeQuery(query)
}
My problem is with this row:
self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.countUnit())
The activity.quantity
returns indeed the right value (156 kcal) but when i try getting the double value from it (as done above) I get libc++abi.dylib: terminating with uncaught exception of type NSException
Any idea why this might happen?
Upvotes: 3
Views: 3075
Reputation: 2645
Thanks to OOPer for his comment. Changing the line to:
self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.kilocalorieUnit())
did the trick.
Upvotes: 7