Get total step count for every date in HealthKit

后端 未结 6 547
南笙
南笙 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条回答
  •  萌比男神i
    2020-11-29 07:00

    Modified @sebastianr's answer using core Swift classes, for just for testing I am returning only steps for just one day, once you have more days you can create a dictionary of Dates and step count and return it

    func getStepCountPerDay(completion:@escaping (_ count: Double)-> Void){
    
        guard let sampleType = HKObjectType.quantityType(forIdentifier: .stepCount)
            else {
                return
        }
        let calendar = Calendar.current
        var dateComponents = DateComponents()
        dateComponents.day = 1
    
        var anchorComponents = calendar.dateComponents([.day, .month, .year], from: Date())
        anchorComponents.hour = 0
        let anchorDate = calendar.date(from: anchorComponents)
    
        let stepsCumulativeQuery = HKStatisticsCollectionQuery(quantityType: sampleType, quantitySamplePredicate: nil, options: .cumulativeSum, anchorDate: anchorDate!, intervalComponents: dateComponents
        )
    
        // Set the results handler
        stepsCumulativeQuery.initialResultsHandler = {query, results, error in
            let endDate = Date()
            let startDate = calendar.date(byAdding: .day, value: 0, to: endDate, 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)")
                        completion(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
        }
        HKHealthStore().execute(stepsCumulativeQuery)
    }
    

提交回复
热议问题