HealthKit - DietaryEnergyConsumed

HealthKit - DietaryEnergyConsumed

晚上好,

我正在开展一个获取 .dietaryEnergyConsumed 的项目,我能够获取单个样本,但无法弄清楚如何获取当天的所有数据并对其求和。非常感谢任何帮助。

获取数据的函数如下:

func getDietaryEnergy() {

    print("getDietaryEnergy()")

    guard let stepSampleType = HKQuantityType.quantityType(forIdentifier: .dietaryEnergyConsumed) else {

        print("Dietary Energy Sample Type is no longer available in HealthKit\n\n")

        return
    }

    self.getMostRecentSample(for: stepSampleType, completion: { (sample, error) in

        guard let sample = sample else {

            return
        }

        print(sample.quantity)

    })

}

这是获取最新样本的查询:

func getMostRecentSample(for sampleType: HKSampleType,
                         completion: @escaping (HKQuantitySample?, Error?) -> Swift.Void) {

    print("getMostRecentSample()")

    //1. Use HKQuery to load the most recent samples.
    let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
                                                          end: Date(),
                                                          options: .strictEndDate)

    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
                                          ascending: false)

    let limit = 1

    let sampleQuery = HKSampleQuery(sampleType: sampleType, predicate: mostRecentPredicate, limit: limit, sortDescriptors: [sortDescriptor]) { (query, samples, error) in

        //2. Always dispatch to the main thread when complete.
        DispatchQueue.main.async {

            guard let samples = samples,
                let mostRecentSample = samples.first as? HKQuantitySample else {

                    completion(nil, error)
                    return
            }

            completion(mostRecentSample, nil)
        }
    }

    HKHealthStore().execute(sampleQuery)
}

因此,我创建了另一个函数来根据开始日期和结束日期执行和汇总样本。这是代码:

//MARK: - Read Dietary Energy
func readDietaryEnergy(date: Date) {
    guard let energyType = HKSampleType.quantityType(forIdentifier: .dietaryEnergyConsumed) else {
        print("Sample type not available")
        return
    }

    let startDate = convertStartDate(StartDate: date)
    let endDate = convertEndDate(EndDate: date)
    let Predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)

    let dietaryEnergyQuery = HKSampleQuery(sampleType: energyType,
                                    predicate: Predicate,
                                    limit: HKObjectQueryNoLimit,
                                    sortDescriptors: nil) {
                                        (query, sample, error) in

                                        guard
                                            error == nil,
                                            let quantitySamples = sample as? [HKQuantitySample] else {
                                                print("Something went wrong: \(String(describing: error))")
                                                return
                                        }

                                        let total = quantitySamples.reduce(0.0) { [=10=] + .quantity.doubleValue(for: HKUnit.kilocalorie()) }
                                        DispatchQueue.main.async {
                                            self.userDietaryEnergy = total
                                        }
    }
    HKHealthStore().execute(dietaryEnergyQuery)
}