Get total step count for every date in HealthKit

后端 未结 6 574
南笙
南笙 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 06:41

    Port to Swift with no dependency to SwiftDate library

        let calendar = NSCalendar.current
        let interval = NSDateComponents()
        interval.day = 1
    
        var anchorComponents = calendar.dateComponents([.day, .month, .year], from: NSDate() as Date)
        anchorComponents.hour = 0
        let anchorDate = calendar.date(from: anchorComponents)
    
        // Define 1-day intervals starting from 0:00
        let stepsQuery = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: interval as DateComponents)
    
        // Set the results handler
        stepsQuery.initialResultsHandler = {query, results, error in
            let endDate = NSDate()
            let startDate = calendar.date(byAdding: .day, value: -7, to: endDate as Date, wrappingComponents: false)
            if let myResults = results{
                myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
                if let quantity = statistics.sumQuantity(){
                    let date = statistics.startDate
                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("\(date): steps = \(steps)")
                    //NOTE: If you are going to update the UI do it in the main thread
                    DispatchQueue.main.async {
                        //update UI components
                    }
    
                }
                } //end block
            } //end if let
        }
        healthStore?.execute(stepsQuery)
    

提交回复
热议问题