John Ramos John Ramos - 4 months ago 26
Swift Question

HealthKit Swift getting today's steps

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 my predicate:

let anHourBeforeNow: NSDate = NSDate().dateByAddingTimeInterval(-60 * 60)
let predicate = HKQuery.predicateForSamplesWithStartDate(anHourBeforeNow, endDate: NSDate(), options: .None)


And I have the rest down, so I can successfully access the user's step count for the last hour. But how can I access the user's step data since the day began, like the Health app displays in the steps section?

I am trying to do something like this:

let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None)


but this code does not adjust for time zone (so it gives me the beginning of the day in UTC, not the beginning of the day where the user is) and I am also getting highly inflated step counts (for reasons unknown).

So how can I get the user's step count for the current day, with the same number of steps as reported in Health, like pictured here:enter image description here

Answer

The query you were using takes all of the user's recorded steps from Healthkit, not doing the smart filter-out of duplicative steps the Health app does. Instead, you want to get the aggregated step data that the Health app produces after combining steps from different sources to get an accurate tally.

To do that, you can use this code:

func recentSteps2(completion: (Double, NSError?) -> () )
{ // this function gives you all of the steps the user has taken since the beginning of the current day.

    checkAuthorization() // checkAuthorization just makes sure user is allowing us to access their health data.
    let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) // The type of data we are requesting


    let date = NSDate()
    let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let newDate = cal.startOfDayForDate(date)
    let predicate = HKQuery.predicateForSamplesWithStartDate(newDate, endDate: NSDate(), options: .None) // Our search predicate which will fetch all steps taken today

    // The actual HealthKit Query which will fetch all of the steps and add them up for us.
    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in
        var steps: Double = 0

        if results?.count > 0
        {
            for result in results as! [HKQuantitySample]
            {
                steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
            }
        }

        completion(steps, error)
    }

    storage.executeQuery(query)
}