ios - HKStatisticsCollectionQuery 工作一天然后停止。如何让更新处理程序无限期地工作?

标签 ios swift healthkit

此代码的目标是监控用户每天消耗的活跃卡路里。现在代码在第 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/

相关文章:

ios - 无法在没有参数的情况下调用类型 'Reachability' 的初始值设定项

swift - 制作扩展 ScrollView

ios - 如何更改属性数组的字体大小(swift,ios)

ios - Command/Xcode.app/Contents/Developer/Toolchains/Swift_2.3.xctoolchain/usr/bin/swiftc 失败,退出代码为 1

ios - 无法使用类型的参数列表调用 'requestAuthorizationToShareTypes'

javascript - React native——动态添加onPress View

php - PHP 加密与 iOS 和 .NET 的区别

ios - 是否可以在 HealthKit 中添加样本描述?

ios - dispatch_group_leave swift 崩溃

ios - Cordova Keychain 插件和 SSKeychain 插件不能一起工作