您好我想在定义的时间间隔中获取最新数据点 每天的体重 (在我的情况下,我需要一个星期的间隔,但只需要每天的最后一个条目。)
实际上,使用此代码我可以获得从开始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查询呢?
我尝试定义排序描述符,但我找不到一种方法让它在定义的时间间隔内工作。
谢谢
答案 0 :(得分:1)
正如您所说,您想要使用排序描述符,只需使用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)
}