有没有办法从 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 天,如果时间段为一个月,则没有多大用处。
有人解决了吗?
最佳答案
我遇到了同样的问题。我想为 iPhone 和 Apple Watch 获取单独的步数。
下面是我是如何做到这一点的。
首先,我们需要一个谓词让设备只获取 Apple Watch 结果。
let watchPredicate = HKQuery.predicateForObjects(withDeviceProperty: HKDevicePropertyKeyModel, allowedValues: ["Watch"])
现在我们可以使用此谓词查询样本,我们将只获取 Apple Watch 条目。
我们还可以在查询中包含更多谓词,使用 NSCompoundPredicate
关于iOS Apple HealthKit 仅限 Apple Watch 步数数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46067646/