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
Using the above answers and from Apple here: https://developer.apple.com/reference/healthkit/hkstatisticsquery I got the following to work in swift 2.3 on Xcode 8.0.
class func getStepCountHealth(startDate: NSDate, endDate: NSDate, completion:(Double?, NSError?)->()) {
let healthKitStore:HKHealthStore = HKHealthStore()
// Define the sample type
let sampleType = HKQuantityType.quantityTypeForIdentifier(
HKQuantityTypeIdentifierStepCount)
// Set the predicate
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate,
endDate: endDate, options: .None)
// build the query
let sampleQuery = HKStatisticsQuery(quantityType: sampleType!,
quantitySamplePredicate: predicate,
options: .CumulativeSum) { query, results, error in
if results != nil {
let quantity = results?.sumQuantity()
let unit = HKUnit.countUnit()
let totalSteps = quantity?.doubleValueForUnit(unit)
completion(totalSteps, error)
// print("totalSteps for \(endDate) are \(totalSteps!)")
} else {
completion(nil, error)
// print("results are nil")
return
}
}
// execute the Query
healthKitStore.executeQuery(sampleQuery)
}