2017-10-19 56 views
0

Apple的文檔示例代碼通過add方法將平均心率HKQuantitySample保存到鍛鍊中,但是對於給定的鍛鍊,我試圖保存在鍛鍊期間採取的所有心率值鍛鍊,即[HKQuantitySample]我該如何做到這一點?下面是我的代碼添加第一個值只是爲了測試,但我想將它們全部添加?如何將HKQuantitySamples(心率)數組保存到鍛鍊

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

我想你錯過了每次心率記錄的時間......你有嗎? – Ladislav

+0

好吧,我可以通過使用'日期'來獲得,但是這將如何被納入? – GarySabo

回答

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方法。 ..