How can I get daily average steps form HealthKit
Asked Answered
A

2

5

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.

Afterdamp answered 2/2, 2015 at 20:16 Comment(6)
So what's your exact problem? What part of your code isn't working and in what way aren't the results what you'd expect?Diligence
I really have a problem, im just stuck. I dont know how to access/add the date stored in the HKQuantitySample ArrayAfterdamp
Are you getting all the data as expected from your query? Is the only part you're struggling with that for loop? You really have to update your question to make it more specific if you want people to help you...Diligence
You're right. I had written more but i was removed.Afterdamp
This is exactly what HKStatisticsQuery and HKStatisticsCollectionQuery are designed to do. Don't do the math yourself, let the framework do it for you! Statistics queries can give you the sum, min, max, and average values for samples matching the predicates you provide.Oceanic
Sounds great, but i can't seem to find an example? do you have one?Afterdamp
D
2

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())
}
Diligence answered 2/2, 2015 at 21:3 Comment(0)
B
10

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.

Best Solution

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.

Bleary answered 6/3, 2015 at 6:48 Comment(1)
This solution works but there's one issue regarding this... It downs't mean that each day you have a sample but all in all you divide by number of days which is not a good result. Imagine that you have 700 steps on Monday and no steps for the rest of the week and in result you get 100 steps a day... This may not be a great result for some apps.Middendorf
D
2

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())
}
Diligence answered 2/2, 2015 at 21:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.