简体   繁体   中英

Why HealthKit returns incorrect time?

I'm trying to get steps count for each hour and for this I do:

func retrieveSteps(completion: @escaping (_ stepsCount: Double) -> Void) {
    let stepsCount = HKQuantityType.quantityType(forIdentifier: .stepCount)

    let date = Date()
    let calendar = Calendar(identifier: .gregorian)
    let newDate = calendar.startOfDay(for: date)

    let predicate = HKQuery.predicateForSamples(withStart: newDate, end: date, options: [.strictStartDate])
    var interval = DateComponents()
    interval.hour = 1

    let query = HKStatisticsCollectionQuery(quantityType: stepsCount!, quantitySamplePredicate: predicate, options: [.cumulativeSum], anchorDate: newDate, intervalComponents: interval)

    query.initialResultsHandler = { query, result, error in
        if let stats = result {
            stats.enumerateStatistics(from: newDate, to: date) { statistics, _ in
                if let quantity = statistics.sumQuantity() {

                    let steps = quantity.doubleValue(for: HKUnit.count())
                    print("Steps: \(steps) for: \(statistics.endDate)")

                    completion(steps)
                }
            }
        }
    }

    HKHealthStore().execute(query)
}

And when I execute it I get incorrect date values. For example:

Steps: 28.3782023430627 for: 2017-10-22 10:00:00 +0000

but on Health app it shows time 11:58 . Why I'm getting 10:00 ? And how can I improve it?

The statistics object you get back from HKStatisticsCollectionQuery represents a range of time the size of the interval components you provided, rather than the date of specific samples that fall inside that time range. If you want to find the date of the most recent step count sample in HealthKit, you should use an HKSampleQuery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM