How to query healthkit data based upon timestamp in Apple health?

Viewed 429

What would be the best approach to collect activity information such as Calories Burned, Exercise time in a specific period of time?

Any approach or hint would be appreciable. Thanks

1 Answers

You can use query classes in HealthKit. For instance:

let calendar = NSCalendar.currentCalendar()
 
let interval = NSDateComponents()
interval.day = 7
 
// Set the anchor date to Monday at 3:00 a.m.
let anchorComponents = calendar.components([.Day, .Month, .Year, .Weekday], fromDate: NSDate())
 
 
let offset = (7 + anchorComponents.weekday - 2) % 7
anchorComponents.day -= offset
anchorComponents.hour = 3
 
guard let anchorDate = calendar.dateFromComponents(anchorComponents) else {
    fatalError("*** unable to create a valid date from the given components ***")
}
 
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount) else {
    fatalError("*** Unable to create a step count type ***")
}
 
// Create the query
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
                                        quantitySamplePredicate: nil,
                                        options: .CumulativeSum,
                                        anchorDate: anchorDate,
                                        intervalComponents: interval)
 
// Set the results handler
query.initialResultsHandler = {
    query, results, error in
    
    guard let statsCollection = results else {
        // Perform proper error handling here
        fatalError("*** An error occurred while calculating the statistics: \(error?.localizedDescription) ***")
    }
    
    let endDate = NSDate()
    
    guard let startDate = calendar.dateByAddingUnit(.Month, value: -3, toDate: endDate, options: []) else {
        fatalError("*** Unable to calculate the start date ***")
    }
    
    // Plot the weekly step counts over the past 3 months
    statsCollection.enumerateStatisticsFromDate(startDate, toDate: endDate) { [unowned self] statistics, stop in
        
        if let quantity = statistics.sumQuantity() {
            let date = statistics.startDate
            let value = quantity.doubleValueForUnit(HKUnit.countUnit())
            
            // Call a custom method to plot each data point.
            self.plotWeeklyStepCount(value, forDate: date)
        }
    }
}
 
healthStore.executeQuery(query)

You need to play with these codes according to your case.

Related