I have a basic step counter app that returns the last weeks' step counts. Today is March 29th, yet the app returns today count as March 21st.
Any thoughts on what's going on?
(I will attach a png of the results if I can). Here is the code that generates that results.
func calculateSteps() async throws {
guard let healthStore = self.healthStore else { return }
let startDate = Calendar.current.date(byAdding: .day, value: -7, to: .startOfDay)
let endDate = Date()
let stepType = HKQuantityType(.stepCount)
let daily = DateComponents(day: 1)
let thisWeek = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
let stepsThisWeek = HKSamplePredicate.quantitySample(type: stepType, predicate: thisWeek)
let sumOfSteps = HKStatisticsCollectionQueryDescriptor(
predicate: stepsThisWeek,
options: .cumulativeSum,
anchorDate: endDate,
intervalComponents: daily
)
let stepsCount = try await sumOfSteps.result(for: healthStore)
guard let startDate = startDate else { return }
stepsCount.enumerateStatistics(from: startDate, to: endDate) { results, end in
let count = results.sumQuantity()?.doubleValue(for: .count())
let step = Step(count: Int(count ?? 0), date: results.startDate)
if step.count > 0 {
self.steps.append(step)
}
}
}
}
Thanks. Blessings, --Mark
I have a basic step counter app that returns the last weeks' step counts. Today is March 29th, yet the app returns today count as March 21st.
Any thoughts on what's going on?
(I will attach a png of the results if I can). Here is the code that generates that results.
func calculateSteps() async throws {
guard let healthStore = self.healthStore else { return }
let startDate = Calendar.current.date(byAdding: .day, value: -7, to: .startOfDay)
let endDate = Date()
let stepType = HKQuantityType(.stepCount)
let daily = DateComponents(day: 1)
let thisWeek = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
let stepsThisWeek = HKSamplePredicate.quantitySample(type: stepType, predicate: thisWeek)
let sumOfSteps = HKStatisticsCollectionQueryDescriptor(
predicate: stepsThisWeek,
options: .cumulativeSum,
anchorDate: endDate,
intervalComponents: daily
)
let stepsCount = try await sumOfSteps.result(for: healthStore)
guard let startDate = startDate else { return }
stepsCount.enumerateStatistics(from: startDate, to: endDate) { results, end in
let count = results.sumQuantity()?.doubleValue(for: .count())
let step = Step(count: Int(count ?? 0), date: results.startDate)
if step.count > 0 {
self.steps.append(step)
}
}
}
}
Thanks. Blessings, --Mark
Share Improve this question asked Mar 29 at 21:35 GarageshopGarageshop 12110 bronze badges1 Answer
Reset to default 0I discovered I had the date: wrong. I had it as results.startDate, and when I flipped it to resuluts.endDate, the data produced was correct.
Thanks.
Blessings, --Mark