I'm trying to display the daily amount of steps the user takes. But I don't really know how to manage this.
I already got this code:
let endDate = NSDate()
let startDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitMonth, value: -1, toDate: endDate, options: nil)
let weightSampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: .None)
let query = HKSampleQuery(sampleType: weightSampleType, predicate: predicate, limit: 0, sortDescriptors: nil, resultsHandler: {
(query, results, error) in
if results == nil {
println("There was an error running the query: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
var dailyAVG = Int()
var steps = results as [HKQuantitySample]
for var i = 0; i < results.count; i++
{
//results[i] add values to dailyAVG
}
}
})
self.healthKitStore.executeQuery(query)
The query gets all the data needed as far as I know. But I don't know how to get the values out of the HKQuantitySample
. So I cant test if the correct values are in the HKQuantitySample
Array.
You need to loop through steps
not results
and then use each HKQuantitySample
result's quantity
property to get the number of steps in that sample, ex:
var dailyAVG:Double = 0
for steps in results as [HKQuantitySample]
{
// add values to dailyAVG
dailyAVG += steps.quantity.doubleValueForUnit(HKUnit.countUnit())
}