我怎样才能获取在规定的时间间隔从HealthKit数据的最近体重条目的每一天
问题描述:
你好,我想抓住最新数据点每天体重的在定义的时间间隔 (在我来说,我需要一个星期的时间间隔,但只有每一天的最后一个项目。)我怎样才能获取在规定的时间间隔从HealthKit数据的最近体重条目的每一天
实际上,使用这个代码,我可以从开始X日起所有条目到最后X日期
let query = HKSampleQuery(sampleType: type!, predicate: predicate,
limit: 0, sortDescriptors: nil, resultsHandler: { (query, results, error) in
if let myResults = results {
for result in myResults {
let bodymass = result as! HKQuantitySample
let weight = bodymass.quantity.doubleValue(for: unit)
Print ("this is my weight value",weight )
}
}
else {
print("There was an error running the query: \(String(describing: error))")
}
此查询返回测量时间范围内所有消耗体重的样本。 我只想返回记录的最后一个条目是否有任何方式与heath-kit查询?
我试过定义排序描述符,但我没有找到一种方法使它在定义的时间间隔内工作。
感谢
答
正如你说你想用一种描述,只是使用Date.distantPast
和Date()
为你的范围,那么就抢到第一:
func getUserBodyMass(completion: @escaping (HKQuantitySample) -> Void) {
guard let weightSampleType = HKSampleType.quantityType(forIdentifier: .bodyMass) else {
print("Body Mass Sample Type is no longer available in HealthKit")
return
}
//1. Use HKQuery to load the most recent samples.
let mostRecentPredicate = HKQuery.predicateForSamples(withStart: Date.distantPast,
end: Date(),
options: [])
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate,
ascending: false)
let limit = 1
let sampleQuery = HKSampleQuery(sampleType: weightSampleType,
predicate: mostRecentPredicate,
limit: limit,
sortDescriptors: [sortDescriptor]) { (query, samples, error) in
//2. Always dispatch to the main thread when complete.
DispatchQueue.main.async {
guard let samples = samples,
let mostRecentSample = samples.first as? HKQuantitySample else {
print("getUserBodyMass sample is missing")
return
}
completion(mostRecentSample)
}
}
healthStore.execute(sampleQuery)
}