[英]Why HealthKit returns incorrect time?
我试图获取每小时的步数,为此,我这样做:
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
获取的统计信息对象表示的是您提供的间隔分量大小的时间范围,而不是落入该时间范围内的特定样本的日期。 如果要在HealthKit中查找最新步骤计数样本的日期,则应使用HKSampleQuery
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.