从Health Kit获取卡路里

时间:2017-04-18 05:06:23

标签: ios swift health-kit

我使用此功能获取与RunKeeper同步后从Health Kit中消耗的卡路里

func getActiveEnergy(currentDate: Date ,completion: @escaping ((_ totalEnergy: Double) -> Void)) {
    let calendar = Calendar.current
    var totalBurnedEnergy = Double()
    let startOfDay = Int((currentDate.timeIntervalSince1970/86400)+1)*86400
    let startOfDayDate = Date(timeIntervalSince1970: Double(startOfDay))
    //   Get the start of the day
    let newDate = calendar.startOfDay(for: startOfDayDate)
    let startDate: Date = calendar.date(byAdding: Calendar.Component.day, value: -1, to: newDate)!

    //  Set the Predicates
    let predicate = HKQuery.predicateForSamples(withStart: startDate as Date, end: newDate as Date, options: .strictStartDate)

    //  Perform the Query
    let energySampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned)

    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)")
        }

        DispatchQueue.main.async {

            for activity in results as! [HKQuantitySample]
            {
                let calories = activity.quantity.doubleValue(for: HKUnit.kilocalorie())
                totalBurnedEnergy = totalBurnedEnergy + calories
            }
            completion(totalBurnedEnergy)
        }
    })
    self.healthStore.execute(query)
}

问题是如果我使用RunKeeper一夜之间收集数据,我每天都无法获得分隔值。例如:

enter image description here

4月17日:3.1 4月18日:4.2

但在我的应用程序中,我只获得以下数据: 4月17日:7.3

4月17日在Health app:

enter image description here

任何想法?

1 个答案:

答案 0 :(得分:0)

通过以下链接解决了问题: {{3}}