My application currently lets users save WaterIntakeRecord
s and they are then persisted with Core Data. I am able to write to HealthKit, saving a water intake record as a HKQuantitySample
.
I add a WaterIntakeRecord
into my application with an amount of 12.9 fluid ounces. Since in Health, I have milliliters as my preferred unit of measurement, it shows in milliliters:
Where I am struggling is when trying to delete a sample.
When the user saves a WaterIntakeRecord
, they can choose the unit of measurement that they want to save the sample in, and then it converts that measurement to US ounces, which is a property of WaterIntakeRecord
. This way, every WaterIntakeRecord
has a consistent unit of measurement that can be converted into other units of measurement (all the ones found in Health) for display.
When trying to delete a saved sample, I try this:
static func deleteWaterIntakeSampleWithAmount(amount: Double, date: NSDate) {
guard let type = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDietaryWater) else {
print("———> Could not retrieve quantity type for identifier")
return
}
let quantity = HKQuantity(unit: HKUnit.fluidOunceUSUnit(), doubleValue: amount)
let sample = HKQuantitySample(type: type, quantity: quantity, startDate: date, endDate: date)
HealthKitStore.deleteObject(sample) { (success, error) -> Void in
if let err = error {
print("———> Could not delete water intake sample from HealthKit: \(err)")
} else {
print("———> Deleted water intake sample from HealthKit")
}
}
}
When the user deletes a record in my application, it should delete the corresponding sample in HealthKit. The record is successfully deleted from my application, however, I keep getting an error when attempting to delete the sample from HealthKit, using the method above:
Error Domain=com.apple.healthkit Code=100 "Transaction failure." UserInfo {NSLocalizedDescription=Transaction failure.}
I'm not sure what I am doing incorrectly to keep getting this error.
The amount
parameter is the WaterIntakeRecord
's ouncesUS
value, and the date
parameter is the WaterIntakeRecord
s date
property which is the creation date of the record:
Any ideas on where I am causing the deletion to fail?