此代码的目标是监控用户每天消耗的活跃卡路里。现在代码在第 1 天完美运行。获取当天消耗的用户卡路里,并全天更新卡路里计数。然而,第二天代码停止工作,它只显示用户在第 1 天燃烧的事件卡路里。如何修复此代码,以便更新处理程序继续获取用户每天燃烧的事件卡路里,而不会在结束时停止第一天。
func getSteps() -> Void {
guard let energyBurnedType = HKObjectType.quantityType(forIdentifier: .activeEnergyBurned) else {
fatalError("*** Unable to get the step count type ***")
}
var interval = DateComponents()
interval.hour = 24
let calendar = Calendar.current
let anchorDate = calendar.date(bySettingHour: 0, minute: 0, second: 0, of: Date())
let query = HKStatisticsCollectionQuery.init(quantityType: energyBurnedType,
quantitySamplePredicate: nil,
options: .cumulativeSum,
anchorDate: anchorDate!,
intervalComponents: interval)
query.initialResultsHandler = {
query, results, error in
DispatchQueue.main.async {
let startDate = calendar.startOfDay(for: Date())
results?.enumerateStatistics(from: startDate,
to: Date(), with: { (result, false) in
self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
}
}
query.statisticsUpdateHandler = {
query, statistics, results, error in
print("update handler set")
DispatchQueue.main.async {
// in order to fix problem of steps not updating at the start of new day I tried using Calendar.current
let currentDay = Calendar.current
let startDate = currentDay.startOfDay(for: Date())
results?.enumerateStatistics(from: startDate,
to: Date(), with: { (result, false) in
self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
}
}
healthStore.execute(query)}}
最佳答案
问题是:
let startDate = currentDay.startOfDay(for: Date())
开始日期不应是今天。
尽量把这个日期定在今天的前几天。
例如:
设置开始日期为今天前 3 天
query.initialResultsHandler = {
query, results, error in
DispatchQueue.main.async {
let startDate = Calendar.current.date(byAdding: .day, value: -3, to: Date())
results?.enumerateStatistics(from: startDate,
to: Date(), with: { (result, false) in
self.moveResult = (Int(result.sumQuantity()?.doubleValue(for: HKUnit.kilocalorie()) ?? 0))})
}
关于ios - HKStatisticsCollectionQuery 工作一天然后停止。如何让更新处理程序无限期地工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516299/