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.

ricardopereira
  • 11,118
  • 5
  • 63
  • 81
Egghead
  • 6,837
  • 5
  • 20
  • 38
  • 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? – Lyndsey Scott Feb 02 '15 at 20:22
  • I really have a problem, im just stuck. I dont know how to access/add the date stored in the HKQuantitySample Array – Egghead Feb 02 '15 at 20:36
  • 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... – Lyndsey Scott Feb 02 '15 at 20:38
  • You're right. I had written more but i was removed. – Egghead Feb 02 '15 at 20:51
  • 1
    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. – Allan Feb 03 '15 at 07:15
  • Sounds great, but i can't seem to find an example? do you have one? – Egghead Feb 03 '15 at 11:35

2 Answers2

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.

ricardopereira
  • 11,118
  • 5
  • 63
  • 81
  • 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. – cojoj Sep 18 '15 at 12:56
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())
}
Lyndsey Scott
  • 37,080
  • 10
  • 92
  • 128