我正在尝试获取过去 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)
}