Get total step count for every date in HealthKit

后端 未结 6 543
南笙
南笙 2020-11-29 06:13

What\'s the best way to get a total step count for every day recorded in HealthKit. With HKSampleQuery\'s method initWithSampleType (see below) I can set a star

6条回答
  •  渐次进展
    2020-11-29 07:00

    Here is a translation that currently works for Swift 2.0, using the SwiftDate library.

        let type = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
        let startDate = NSDate().beginningOfDay().oneWeekAgo()
        let interval = NSDateComponents()
        interval.day = 1
    
        let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: NSDate(), options: .StrictStartDate)
        let query = HKStatisticsCollectionQuery(quantityType: type!, quantitySamplePredicate: predicate, options: [.CumulativeSum], anchorDate: NSDate().begginingOfDay(), intervalComponents:interval)
    
        query.initialResultsHandler = { query, results, error in
    
    
            let endDate = NSDate()
            let startDate = NSDate().beginningOfDay().oneWeekAgo()
            if let myResults = results{
                myResults.enumerateStatisticsFromDate(startDate, toDate: endDate) {
                    statistics, stop in
    
                    if let quantity = statistics.sumQuantity() {
    
                        let date = statistics.startDate
                        let steps = quantity.doubleValueForUnit(HKUnit.countUnit())
                        print("\(date): steps = \(steps)")
                    }
                }
            }
        }
    
        healthKitStore.executeQuery(query)
    

提交回复
热议问题