问题
Using HealthKit, I am saving below data:
- Workout
- Active Energy
- Distance
I am deleting workout using below code:
self.healthStore?.delete(workout, withCompletion: { (status, error) in
But above code just deletes a workout from HealthKit app. I want to delete workout and it's associated samples. How can i do this?
回答1:
To delete associated samples we need to perform delete query on specific HKQuantityTypeIdentifier
.
To delete Active Energy from Workout refer below code:
let energyBurnedQuantity = HKQuantityType.quantityType(forIdentifier: .activeEnergyBurned)
let predicate = HKQuery.predicateForObjects(from: workout)
let energyQuery = HKSampleQuery(sampleType: energyBurnedQuantity!, predicate: predicate, limit: 100, sortDescriptors: nil) { (query, result, error) in
if error == nil {
guard let resultData = result else {
return
}
if resultData.count > 0 {
self.healthStore?.delete(resultData, withCompletion: { [unowned self] (status, error) in
if status == true {
print("Successfully deleted Energy.")
})
} else {
print("Error \(String(describing: error?.localizedDescription))")
}
})
}
}
}
self.healthStore?.execute(energyQuery)
来源:https://stackoverflow.com/questions/56055720/healthkit-issue-with-associated-samples-deletion-of-provided-workout