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

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

但在健康应用程序中,它显示时间11:58。为什么我会得到10:00?我该怎么改进呢?

最佳答案

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

关于ios - 为什么HealthKit返回不正确的时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46872849/

10-12 00:40
查看更多