【问题标题】:sumQuantity in HKStatisticsCollectionQuery returns nil when fetching step count on hourly basis每小时获取步数时,HKStatisticsCollectionQuery 中的 sumQuantity 返回 nil
【发布时间】:2025-11-25 22:20:03
【问题描述】:

我想按小时从 Health 应用中获取步数。

但下面代码中的 statistics.sumQuantity() 总是返回 nil 值。

注意:因为我希望在同一天内按小时计算步数,所以我通过 startDate 和 endDate 两者都是相同的。

在下面的代码中输出总是,没有步数。

let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options:[ .strictStartDate])
    
var interval = DateComponents()
interval.hour = 1

let query = HKStatisticsCollectionQuery(quantityType: sampleType,
                                        quantitySamplePredicate: predicate,
                                        options: [.cumulativeSum],
                                        anchorDate: startDate,
                                        intervalComponents: interval)

query.initialResultsHandler = { query, statsCollection, error in
    if error != nil {
        completion(nil, error)
        return
    }

    var totalSum = 0.0
    if let myResults = statsCollection { myResults.enumerateStatistics(from: startDate, to: startDate) { statistics, stop in

            if let quantity = statistics.sumQuantity() {
                let date = statistics.startDate
                let steps = quantity.doubleValue(for: HKUnit.count()) 
                totalSum = totalSum + steps
            } else {
                print("No step quantity")
                let steps = 0.0
                let date = statistics.startDate
            }
        }
    }
    
    DispatchQueue.main.async {

    }
}
self.healthStore.execute(query)

【问题讨论】:

    标签: ios swift healthkit


    【解决方案1】:

    您的startDateendDate 不能相同。即使您正在查看同一天内的步骤,您仍应将 startDate 设置为一天的开始:

    startDate = Calendar.current.startOfDay(for: Date())
    endDate = Date()
    

    【讨论】: