【问题标题】:HKSampleQuery will only return values from past 7 days?HKSampleQuery 只会返回过去 7 天的值?
【发布时间】:2018-07-20 22:03:59
【问题描述】:

这是一个 WatchOS 应用程序。通过测试,该代码似乎只会返回我手动添加到健康应用程序中的小于 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 上运行此代码?
  • @Allan 是的,为什么?

标签: ios swift apple-watch healthkit watchos-4


【解决方案1】:

watchOS 上的 HealthKit 仅提供对上周数据的访问。您可以使用HKHealthStore 方法earliestPermittedSampleDate 来查询确切的日期。如果您需要从 HealthKit 查询可能超过一周的历史样本,您应该使用您的配套 iOS 应用程序执行此操作,然后使用 WatchConnectivity 将相关信息发送到您的 watchOS 应用程序。

【讨论】:

  • 希望我能在几天前​​找到您的答案。这绝对是正确的答案。我在寻找我的应用程序内部损坏的东西时苦苦挣扎,但最后发现问题与样本日期有关。我设法通过 WCSession 推送所需的值来解决我的问题。所以,当手表没有找到任何东西时,它至少可以依赖一个缓存值。
猜你喜欢
  • 2020-07-27
  • 1970-01-01
  • 2022-07-20
  • 2017-03-20
  • 1970-01-01
  • 2013-01-25
  • 2014-08-07
  • 2020-03-26
  • 2010-11-22
相关资源
最近更新 更多