如何将一系列HKQuantitySamples(心率)保存到锻炼中

时间:2017-10-19 17:16:07

标签: ios swift health-kit

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
            }


            }
        }

1 个答案:

答案 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
        }


        }
    }

基本上,您创建一个示例数组,添加totalEnergyBurnedSampletotalDistanceSample,然后添加整个heartRateValues数组,然后在sample方法中传递healthStore.add参数。