gpt4 book ai didi

ios - 如何获取最近 7 天的健康数据

转载 作者:行者123 更新时间:2023-11-28 10:10:09 25 4
gpt4 key购买 nike

我正在尝试获取过去 7 天的步数,但找不到具体操作方法。 我想要接收的是一个包含 7 个元素的数组,其中每个元素都是一天,并带有相应的总步数。我目前有这段代码,它获得了今天的步骤:

//Gets the steps
func getTodaysSteps(completion: @escaping (Double) -> Void) {
let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

let now = Date()
let startOfDay = Calendar.current.startOfDay(for: now)
let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
guard let result = result, let sum = result.sumQuantity() else {
print("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
completion(0.0)
return
}

DispatchQueue.main.async {
completion(sum.doubleValue(for: HKUnit.count()))
}
}
healthKitStore.execute(query)
}

我这样调用这个函数:

getTodaysSteps { (steps) in
self.stepsNumber = Int(steps)
}

最佳答案

尝试使用 HKStatisticsCollectionQuery,它将为您计算日期并自动对结果进行存储。以下示例应提供过去 7 天的步数:

    let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

let now = Date()
let exactlySevenDaysAgo = Calendar.current.date(byAdding: DateComponents(day: -7), to: now)!
let startOfSevenDaysAgo = Calendar.current.startOfDay(for: exactlySevenDaysAgo)
let predicate = HKQuery.predicateForSamples(withStart: startOfSevenDaysAgo, end: now, options: .strictStartDate)

let query = HKStatisticsCollectionQuery.init(quantityType: stepsQuantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: startOfSevenDaysAgo,
intervalComponents: DateComponents(day: 1))

query.initialResultsHandler = { query, results, error in
guard let statsCollection = results else {
// Perform proper error handling here...
}

statsCollection.enumerateStatistics(from: startOfSevenDaysAgo, to: now) { statistics, stop in

if let quantity = statistics.sumQuantity() {
let stepValue = quantity.doubleValueForUnit(HKUnit.countUnit())
// ...
}
}
}

关于ios - 如何获取最近 7 天的健康数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com