我正在研究一种从健康套件中读取活动能量(kcal)的方法,但是从HKQuantity获取双重值时遇到问题。 我的代码如下所示:
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)
}
我的问题在于这一行:
self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.countUnit())
activity.quantity
确实返回正确的值( 156 kcal )但是当我尝试从中获取双精度值时(如上所述)我得到libc++abi.dylib: terminating with uncaught exception of type NSException
知道为什么会这样吗?
答案 0 :(得分:4)
感谢OOPer的评论。将行更改为:
self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.kilocalorieUnit())
做了这个伎俩。