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