在HealthKit中查询心率(Heart Rates)数据可以通过两种方式获得:传统的HKQuantitySamples和累积数量样本(Cumulative Quantity Samples)。下面我将详细介绍这两种方式的基础概念、优势、类型、应用场景以及如何进行查询。
import HealthKit
func queryHeartRateSamples() {
guard let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
return
}
let calendar = NSCalendar.current
let startDate = calendar.date(byAdding: .day, value: -7, to: Date())!
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, samples, error) in
guard let samples = samples else {
print("An error occurred: \(error?.localizedDescription ?? "Unknown error")")
return
}
for sample in samples {
guard let quantitySample = sample as? HKQuantitySample else { continue }
let heartRate = quantitySample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minuteUnit()))
print("Heart Rate: \(heartRate) bpm")
}
}
HKHealthStore().execute(query)
}
import HealthKit
func queryCumulativeHeartRateSamples() {
guard let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate) else {
return
}
let calendar = NSCalendar.current
let startDate = calendar.date(byAdding: .day, value: -7, to: Date())!
let endDate = Date()
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [.cumulativeSum])
let query = HKSampleQuery(sampleType: heartRateType, predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, samples, error) in
guard let samples = samples else {
print("An error occurred: \(error?.localizedDescription ?? "Unknown error")")
return
}
for sample in samples {
guard let cumulativeSample = sample as? HKQuantitySample else { continue }
let heartRate = cumulativeSample.quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minuteUnit()))
print("Cumulative Heart Rate: \(heartRate) bpm")
}
}
HKHealthStore().execute(query)
}
通过上述代码示例和解释,您可以在HealthKit中查询心率数据,并根据需要选择使用HKQuantitySamples或累积数量样本。
领取专属 10元无门槛券
手把手带您无忧上云