HKQuantity 翻倍 - 从 Healthkit 获得活性能量值

HKQuantity to Double - getting Active Energy Value from Healthkit

我正在研究一种从健康工具包中读取活性能量 (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 returns 确实是正确的值 (156 kcal) 但是当我尝试从中获取双倍值时(如上所述)我得到 libc++abi.dylib: terminating with uncaught exception of type NSException

知道为什么会发生这种情况吗?

感谢 OOPer 的评论。将行更改为:

self.todayActiveEnergy = activity.quantity.doubleValueForUnit(HKUnit.kilocalorieUnit())

成功了。