Apple的文档示例代码通过HKQuantitySample
方法将平均心率add
保存到锻炼中,但是对于给定的锻炼,我试图保存锻炼期间拍摄的所有心率值,即[HKQuantitySample]
我该怎么做?下面是我的代码添加第一个值只是为了测试,但我想将它们全部添加?
var heartRateValues = [HKQuantitySample]()
func processHeartRateSamples(_ samples: [HKQuantitySample]) {
for sample in samples {
heartRateValues.append(sample)
}
}
private func addSamples(toWorkout workout: HKWorkout, from startDate: Date, to endDate: Date) {
// Create energy and distance samples
let totalEnergyBurnedSample = HKQuantitySample(type: HKQuantityType.activeEnergyBurned(),
quantity: totalEnergyBurnedQuantity(),
start: startDate,
end: endDate)
let totalDistanceSample = HKQuantitySample(type: HKQuantityType.distanceWalkingRunning(),
quantity: totalDistanceQuantity(),
start: startDate,
end: endDate)
// Add samples to workout
healthStore.add([totalEnergyBurnedSample, totalDistanceSample, heartRateValues.first!], to: workout) { (success: Bool, error: Error?) in
guard success else {
print("Adding workout subsamples failed with error: \(String(describing: error))")
return
}
}
}
答案 0 :(得分:2)
您已经heartRateValues
作为[HKQuantitySample]
,所以就这样做:
private func addSamples(toWorkout workout: HKWorkout, from startDate: Date, to endDate: Date) {
// Create energy and distance samples
let totalEnergyBurnedSample = HKQuantitySample(type: HKQuantityType.activeEnergyBurned(),
quantity: totalEnergyBurnedQuantity(),
start: startDate,
end: endDate)
let totalDistanceSample = HKQuantitySample(type: HKQuantityType.distanceWalkingRunning(),
quantity: totalDistanceQuantity(),
start: startDate,
end: endDate)
let samples = [HKQuantitySample]()
samples.append(totalEnergyBurnedSample)
samples.append(totalDistanceSample)
samples.append(contentsOf: heartRateValues)
// Add samples to workout
healthStore.add(samples, to: workout) { (success: Bool, error: Error?) in
guard success else {
print("Adding workout subsamples failed with error: \(String(describing: error))")
return
}
}
}
基本上,您创建一个示例数组,添加totalEnergyBurnedSample
和totalDistanceSample
,然后添加整个heartRateValues
数组,然后在sample
方法中传递healthStore.add
参数。