gpt4 book ai didi

ios - 如何在定义的时间间隔内每天从 HealthKit 数据中获取最新的体重条目

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

您好,我想在定义的时间间隔中获取每天体重的最新数据点(在我的例子中,我需要它间隔一周,但只需要每天的最后一个条目。)

实际上,使用这段代码我可以获得从开始 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 查询来实现吗?

我试图定义排序描述符,但我没有找到一种方法让它在定义的时间间隔内工作。

谢谢

I read thisthis one

最佳答案

正如您所说,您想要使用排序描述符,只需使用 Date.distantPastDate() 作为您的范围,然后只获取第一个:

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)
}

关于ios - 如何在定义的时间间隔内每天从 HealthKit 数据中获取最新的体重条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46712731/

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