Hi, for my first Swift project, I'm making a water tracker and I'm having some trouble getting HealthKit data. If I set the time interval to 1 day, I am able to pull accurate water amounts, but I want to pull data accurate down to the hour instead.
The problem is when I set the interval to the hour, I end up with a bunch of nil samples with only one entry throughout the day actually being filled even though it returns the proper amount of samples. The sample that is populated seems to be random, even with proper HealthKit authorization.
Is there something I need to do to pull smaller time increments other than just setting the interval to be smaller?
func getWater(completion: @escaping(HKStatisticsCollection?) -> Void) {
let waterType = HKQuantityType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.dietaryWater)!
let startDate = Calendar.current.date(byAdding: .day, value: -365, to: Date())
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: Date())
let anchorDate = Date.mondayAt12AM()
let hour = DateComponents(day: 1)
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictEndDate)
query = HKStatisticsCollectionQuery(quantityType: waterType, quantitySamplePredicate: predicate, options: .cumulativeSum, anchorDate: anchorDate, intervalComponents: hour)
query!.initialResultsHandler = { query, statisticsCollection, error in
completion(statisticsCollection)
}
if let healthStore = healthStore, let query = self.query {
healthStore.execute(query)
}
}