Reputation: 624
I'm making an app with HealthKit and want to try to add a swipe to delete on my table view. I know there is a healthStore.delete
option, but will this delete from the Health app and how would I know which HKSample
to delete from HealthKit.
Upvotes: 2
Views: 2584
Reputation: 131
In the first step, you need to define your specific key in HKMetadataKeySyncIdentifier before you save your data to apple health. And then, you can use HKMetadataKeySyncIdentifier to delete specific health data.
let healthKitStore = HKHealthStore()
// SAVE
var meta = [String: Any]()
meta[HKMetadataKeySyncVersion] = 1
meta[HKMetadataKeySyncIdentifier] = "specific key"
let recordSample = HKQuantitySample(type: type, quantity: quantity, start: date, end: date, metadata: meta)
healthKitStore.save(bloodGlucoseSample) { success, error in
if success {
print("saving record to health success")
} else {
print("saving record to health error = \(String(describing: error))")
}
}
// DELETE
let predicate = HKQuery.predicateForObjects(withMetadataKey: HKMetadataKeySyncIdentifier, allowedValues: ["specific key"])
healthKitStore.deleteObjects(of: bloodGlucoseType, predicate: predicate) { success, _, error in
if success {
print("delete health record success")
} else {
print("delete health record error = \(String(describing: error))")
}
}
Upvotes: 2
Reputation: 7363
Yes, calling healthStore.deleteObject()
will delete the sample from Health. However, keep in mind that your app may only delete samples that it saved to HealthKit.
You'll need to perform a query to retrieve the samples you want to show to the user. You could use HKSampleQuery
or HKAnchoredObjectQuery
.
Upvotes: 1
Reputation: 423
The HKSample
class is an abstract class. Thus you should should never instantiate a HKSample
object directly. Instead, you always work with one of the subclasses of HKSample
(HKCategorySample
, HKQuantitySample
, HKCorrelation
, or HKWorkout
classes) where HKSampleClass1
would be one of the subclasses.
healthStore.deleteObject(HKSampleClass1) { (success: Bool, error: NSError?) -> Void in {
if success () {
//success in deletion
}
}}
Upvotes: 2