Skip to content

Instantly share code, notes, and snippets.

@KrishanMadushanka
Created January 1, 2023 16:30
Show Gist options
  • Select an option

  • Save KrishanMadushanka/8c190faa415a55f719ffaca6ee5f39e7 to your computer and use it in GitHub Desktop.

Select an option

Save KrishanMadushanka/8c190faa415a55f719ffaca6ee5f39e7 to your computer and use it in GitHub Desktop.
func readHourlyTotalStepCount() {
guard let stepCountType = HKObjectType.quantityType(forIdentifier: .stepCount) else {
fatalError("*** Unable to get the step count type ***")
}
var interval = DateComponents()
interval.hour = 1
let calendar = Calendar.current
let anchorDate = calendar.date(bySettingHour: 0, minute: 55, second: 0, of: Date())
let query = HKStatisticsCollectionQuery.init(quantityType: stepCountType,
quantitySamplePredicate: nil,
options: .cumulativeSum,
anchorDate: anchorDate!,
intervalComponents: interval)
query.initialResultsHandler = { query, results, error in
let startDate = calendar.date(byAdding: .hour,value: -24, to: Date())
results?.enumerateStatistics(from: startDate!,to: Date(), with: { (result, stop) in
print("Time: \(result.startDate) -\(result.endDate), \(result.sumQuantity()?.doubleValue(for: HKUnit.count()) ?? 0)")
})
}
healthStore.execute(query)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment