swifthealthkit

Saving 'HKQuantitySample' to 'HKHealthStore' does not update its 'sourceRevision' inside 'completion'


When I save new data to HealthKit by creating HKQuantitySample inside the withCompletion of HKHealthStore.save(_:withCompletion:) when I check sourceRevision it is <uninitialized>:

Here is my code:

let dietaryWaterQuantity = HKQuantity(unit: HKUnit.literUnit(with: .milli), doubleValue: 100)
let dietaryWaterSample = HKQuantitySample(type: HKSampleType.quantityType(forIdentifier: .dietaryWater)!,
                                          quantity: dietaryWaterQuantity,
                                          start: Date(),
                                          end: Date())

HKHealthStore().save(dietaryWaterSample) { success, error in
   /// dietaryWaterSample.sourceRevision is <uninitialized> so I cannot use dietaryWaterSample.sourceRevision.source.bundleIdentifier
}

Any ideas are welcomed.


Solution

  • From the documentation for the sourceRevision property (emphasis mine):

    The source revision property is only available on objects you have retrieved from the HealthKit store. When you create a new object, the source revision is set to nil. The system automatically sets this property to represent the current version of the app that saved the object to the HealthKit store. The source revision is then available the next time the object is retrieved from the store.

    Based on that last statement, you must retrieve the object from the store before you will have access to a valid sourceRevision. The original saved instance is not updated via a call to save.