HealthKit-DietaryEnergyConsumed

问题描述 投票:0回答:1

晚上好,

我正在一个项目中获取.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)
}
ios swift healthkit
1个回答
0
投票

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

//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) { $0 + $1.quantity.doubleValue(for: HKUnit.kilocalorie()) }
                                        DispatchQueue.main.async {
                                            self.userDietaryEnergy = total
                                        }
    }
    HKHealthStore().execute(dietaryEnergyQuery)
}
© www.soinside.com 2019 - 2024. All rights reserved.