Reputation: 7017
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.
Upvotes: 5
Views: 5567
Reputation: 101
In case anyone else is trying to solve this in a not-so-terrible way...
At this time, it doesn't look like using HKStatisticsQuery
or HKStatisticsCollectionQuery
is possible for getting average step count. You can only use HKStatisticsOptionDiscreteAverage
on a discrete data type. If you look at the header for HKTypeIdentifiers
, you will see that HKQuantityTypeIdentifierStepCount
is a cumulative data type.
If you try and fetch the average step count, Xcode spits out: Statistics option HKStatisticsOptionDiscreteAverage is not compatible with cumulative data type HKQuantityTypeIdentifierStepCount.
Get the total number of steps a user has taken. You can specify a time period between two dates. Divide the total number of steps by however many days are between your two dates.
Upvotes: 10
Reputation: 37290
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())
}
Upvotes: 2