iOS Apple HealthKit 仅限 Apple Watch 步数数据

标签 ios swift apple-watch healthkit

有没有办法从 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/

相关文章:

ios - 当我收到 Parse 的推送通知时,如何播放声音?

ios - 如何使 "freeform"UIViewController 适应多种屏幕尺寸?

ios - 如何将自定义标记从服务器添加到谷歌地图? swift

swift - 快速获取瞬时心跳数据

ios - 我想使用我的 iOS 应用程序在 Facebook 墙上发布带有自定义文本的视频

swift - CoreData 不持久?

ios - 闭包与委托(delegate)模式

ios - 无效的设备状态 - Xcode/iOS 模拟器错误

swift - iPhone 和 Watch 之间共享数据的 App Group 孤儿功能

ios - 使用迦太基将 CosmicMind Material 稳定版与 Swift 3 一起使用