【发布时间】:2017-09-06 05:46:11
【问题描述】:
有没有办法从 HealthKit 数据库中只获取 Apple Watch 步数数据。我已经完成了 Swift 3 中的示例,并且有工作代码来获取 Apple 提供的合并数据,但其中包含来自 iPhone 和 Apple Watch 的步骤数据。
我还没有看到任何人能够将这两条数据分开的例子。我见过的每个例子都只给出了合并的步骤数据。我可以迭代步数数据源,但不能使用源标识符来获取特定日历时间段的步数数据。
我看到的所有 Swift 3 代码都遵循以下几行(Objective-C 代码遵循类似的功能):
// Request the step count.
let stepType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
//let predicate = HKQuery.predicateForObjects(from: watchsource)
let predicate = HKQuery.predicateForSamples(withStart: startdate, end: enddate, options: [])
// Order doesn't matter, as we are receiving a quantity.
let sortDescriptor = NSSortDescriptor(key:HKSampleSortIdentifierEndDate, ascending:false)
// Fetch the steps.
let query = HKSampleQuery(sampleType:stepType!, predicate: predicate, limit: 0, sortDescriptors:[sortDescriptor]) { query, results, error in
var steps: Double = 0
if results != nil {
if results!.count > 0
{
for result in results as! [HKQuantitySample]
{
steps += result.quantity.doubleValue(for: HKUnit.count())
}
} // if results
} // if results != nil
completion(steps, error as NSError?)
} // HKSampleQuery()
healthKitStore.execute(query)
上述代码作为正确 HealthKit 身份验证的一部分工作正常,我能够获取任何时间段的步骤数据。
然而,HKSampleQuery() 或其他衍生的 HealthKit 库调用似乎无法用于特定来源,即仅 Apple Watch 数据,而不需要 Apple Watch 本身上的应用程序来读取步骤数据。
是的,我知道人们可以读取 iPhone 计步器数据,然后从总步数中减去该数据,但计步器数据仅保留 7 天,如果时间段是一个月,这并没有多大用处。
有人解决了吗?
【问题讨论】:
-
不要使用 HKSampleQuery 来统计数量样本。 HKStatisticsQuery 将为您汇总它们并处理重叠数据,而您采用的方法却没有。
-
谢谢艾伦,我会按照您的建议研究统计方面的问题。干杯,莱因霍尔德。
标签: ios swift apple-watch healthkit