Search code examples
iosswiftswift3apple-watchhealthkit

How to get HealthKit total steps for previous dates


I am trying to get steps from Health Kit, its working fine for mobile but when i connect Apple Watch my app get more steps then Health kit. i trace it and find that it collect detail record of steps but total steps are less then detail in Health kit.

My App getting the sum of these steps:

enter image description here

But I want To Get these:

enter image description here

Here is My Code:

func MultipleDaysStepsAndActivitiesTest(_ startDate:Date, completion: @escaping (NSDictionary, [HealthKitManuallActivity], NSError?) -> () ) {
    let type = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount) // The type of data we are requesting

    let now = Date()

    let newDate = startDate

    let predicate = HKQuery.predicateForSamples(withStart: newDate, end: now, options: HKQueryOptions())

    var dates = now.datesBetweenGivenDates(startDate,endDate:now)
    dates = dates.reversed()

    let query = HKSampleQuery(sampleType: type!, predicate: predicate, limit: 0, sortDescriptors: nil) { query, results, error in

        var dict:[String:Double] = [:]

        if results?.count > 0 {

            for result in results as! [HKQuantitySample] {
                print(result)
                if result.sourceRevision.source.name != kHealthKitSource {

                    if dict[self.fmt.string(from: result.startDate)] != nil {
                        dict[self.fmt.string(from: result.startDate)] = dict[self.fmt.string(from: result.startDate)]! + result.quantity.doubleValue(for: HKUnit.count())

                    } else {
                        dict[self.fmt.string(from: result.startDate)] = result.quantity.doubleValue(for: HKUnit.count())
                    }
                }
            }
        }

        var sDate = startDate // first date
        let cal = Calendar.current
        print(dict)

        if dict.isEmpty {

            while sDate <= Date() {
                dict[self.fmt.string(from: sDate)] = 0
                sDate = cal.date(byAdding: .day, value: 1, to: sDate)!
            }

        } else {

            while sDate <= Date() {

                if dict[self.fmt.string(from: sDate)] == nil {
                    dict[self.fmt.string(from: sDate)] = 0
                }

                sDate = cal.date(byAdding: .day, value: 1, to: sDate)!
            }
        }

        // reading activities
        self.MultipleDaysWorkouts(startDate, endDate: now, completion: { (activities, error) in

            if results?.count == 0 {

                for activity in activities {
                    dict[activity.startDate] = 0.0
                }
            }

            // reading mindfulness activities

            self.MultipleDayMindFullnessActivity(startDate, completion: { (mindfulnessActivities, mindError) in

                if mindError == nil {

                    let allActivities = mindfulnessActivities + activities
                    completion(dict as NSDictionary, allActivities, mindError as NSError?)

                }

            })

        })

    }

    execute(query)
}

Solution

  • You should use HKStatisticsQuery or HKStatisticsCollectionQuery instead of HKSampleQuery. The statistics queries will de-deuplicate overlapping step samples from different sources to ensure that you do not double-count them. You can find documentation for them here and here.