swifthealthkithkhealthstore

HealthKit : Issue with associated samples deletion of provided workout


Using HealthKit, I am saving below data:

  1. Workout
  2. Active Energy
  3. 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?


Solution

  • 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)