为什么HealthKit会返回错误的时间?

时间:2017-10-22 10:09:05

标签: ios swift health-kit

我试图计算每小时的步数,为此我做了:

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)
}

当我执行它时,我得到不正确的日期值。例如:

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

但在Health应用中,它会显示时间11:58。我为什么要10:00?我该如何改进呢?

1 个答案:

答案 0 :(得分:1)

HKStatisticsCollectionQuery返回的统计对象表示您提供的区间组件大小的时间范围,而不是该时间范围内的特定样本的日期。如果要在HealthKit中查找最新步数计数样本的日期,则应使用HKSampleQuery