HealthKit - DietaryEnergyConsumed - PullRequest
       14

HealthKit - DietaryEnergyConsumed

0 голосов
/ 04 апреля 2020

Добрый вечер,

Я работаю над проектом, чтобы получить .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)
}

1 Ответ

0 голосов
/ 10 апреля 2020

Итак, я создал другую функцию для выполнения и суммирования выборок на основе даты начала и окончания. Вот код:

//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)
}
...