I am making a swift iOS app that integrates with a user's step count as reported by the Health app. I can easily find the user's step count in the last hour, using this as my predicate:
let anHourBeforeNow: NSDate = NSDate().dateByAddingTimeInterval(-60 * 60)
let predicate = HKQuery.predicateForSamplesWithStartDate(anHourBeforeNow, endDate: NSDate(), options: .None)
And I have the rest down, so I can successfully access the user's step count for the last hour. But how can I access the user's step data since the day began, like the Health app displays in the steps section?
I am trying to do something like this:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None)
but this code does not adjust for time zone (so it gives me the beginning of the day in UTC, not the beginning of the day where the user is) and I am also getting highly inflated step counts (for reasons unknown).
So how can I get the user's step count for the current day, with the same number of steps as reported in Health, like pictured here:
HKStatisticsCollectionQuery is better suited to use when you want to retrieve data over a time span. Use HKStatisticsQuery to just get the steps for a specific date.
Swift 5:
let healthStore = HKHealthStore()
func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(
withStart: startOfDay,
end: now,
options: .strictStartDate
)
let query = HKStatisticsQuery(
quantityType: stepsQuantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum
) { _, result, _ in
guard let result = result, let sum = result.sumQuantity() else {
completion(0.0)
return
}
completion(sum.doubleValue(for: HKUnit.count()))
}
healthStore.execute(query)
}