[英]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
. 但在“健康”应用程序上,它显示时间11:58
。 Why I'm getting 10:00
? 为什么我要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. 您从HKStatisticsCollectionQuery
获取的统计信息对象表示的是您提供的间隔分量大小的时间范围,而不是落入该时间范围内的特定样本的日期。 If you want to find the date of the most recent step count sample in HealthKit, you should use an HKSampleQuery
. 如果要在HealthKit中查找最新步骤计数样本的日期,则应使用HKSampleQuery
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.