HKSampleQuery 只会 return 过去 7 天的值?
HKSampleQuery will only return values from past 7 days?
这是一款 WatchOS 应用程序。通过测试,似乎这段代码只会 return 我手动添加到健康应用程序中的不到 1 周的任何体重值。这是故意的吗?周围的方式?
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)
}
watchOS 上的 HealthKit 仅提供对上周数据的访问。您可以使用 HKHealthStore
方法 earliestPermittedSampleDate 来查询确切的日期。如果您需要从 HealthKit 查询可能超过一周的历史样本,您应该使用您的配套 iOS 应用程序执行此操作,然后使用 WatchConnectivity 将相关信息发送到您的 watchOS 应用程序。
这是一款 WatchOS 应用程序。通过测试,似乎这段代码只会 return 我手动添加到健康应用程序中的不到 1 周的任何体重值。这是故意的吗?周围的方式?
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)
}
watchOS 上的 HealthKit 仅提供对上周数据的访问。您可以使用 HKHealthStore
方法 earliestPermittedSampleDate 来查询确切的日期。如果您需要从 HealthKit 查询可能超过一周的历史样本,您应该使用您的配套 iOS 应用程序执行此操作,然后使用 WatchConnectivity 将相关信息发送到您的 watchOS 应用程序。