首页 > 解决方案 > iOS Swift,如何区分使用 Apple Watch 和 iPhone 的步骤?

问题描述

我正在使用 HealthKit 框架从使用 HKSource 的用户那里检索步骤。在 Xcode Objective C 中,我使用 Bundle Identifier 来区分来自 watch/iPhone 的步骤。但是使用 Swift 我无法做到这一点。请建议。

提前致谢。

标签: iosswiftapple-watchhealthkithksamplequery

解决方案


.separateBySource在查询的选项中使用。例如:

guard let sampleType = HKObjectType.quantityType(forIdentifier: .stepCount)
    else {
        fatalError("Couldn't create the quantityType for .stepCount")
}
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.day = 1

var anchorComponents = calendar.dateComponents([.day, .month, .year], from: Date())
anchorComponents.hour = 0
guard let anchorDate = calendar.date(from: anchorComponents) else {
    fatalError("Couldn't get the anchor date")
}

let stepsCumulativeQuery =
    HKStatisticsCollectionQuery(quantityType: sampleType,
                                quantitySamplePredicate: nil,
                                options: [.cumulativeSum , .separateBySource],
                                anchorDate: anchorDate,
                                intervalComponents: dateComponents)

推荐阅读