HealthKit Error "Failed to find some objects for deletion" when attempting to delete HKWorkout

224 views Asked by At

I've had a long running problem of receiving this error from HealthKit when attempting to "modify" an HKWorkout by (1) copying an existing workout (2) updating the metadata (3) deleting the "old" workout (selectedWorkout in my code below) then (4) saving the new modified workout. 98% of the time this code works flawlessly, however 2% of the time I will get this error and I end up with duplicate workouts. Am I doing anything wrong?

As an aside I really wish HealthKit would let us modify data so that this dance wasn't necessary.

class func updateMetadataDeleteOldAndSaveNewWorkout(selectedWorkout: HKWorkout, handler: @escaping (Bool,WorkoutManagerError? ) -> Void) {   

    //configure metadata   

    //  Create a new workout with the old workout's fields and new edited metadata object
                let newWorkout = HKWorkout(activityType: selectedWorkout.workoutActivityType, start: selectedWorkout.startDate, end: selectedWorkout.endDate, duration: selectedWorkout.duration, totalEnergyBurned: selectedWorkout.totalEnergyBurned, totalDistance: selectedWorkout.totalDistance, metadata: metadata)

                // Delete the old workout
                HealthStoreSingleton.sharedInstance.healthStore.delete(selectedWorkout, withCompletion: { (success, error) in

                    DispatchQueue.main.async {

                     if let unwrappedError = error  {
                         handler(false, WorkoutManagerError.deleteError(unwrappedError.localizedDescription))
                        return 
                     }
                    }

                    //  When delete was successful save the new workout
                    HealthStoreSingleton.sharedInstance.healthStore.save(newWorkout) { success, error in

                        DispatchQueue.main.async {
                            if let unwrappedError = error {
                                handler(false, WorkoutManagerError.saveError(unwrappedError.localizedDescription))
                                return 
                            }

                            if success {

                                handler(true, nil)
                                return 
                            } else {
                                  handler(false, WorkoutManagerError.saveError("\(String(describing: error))"))
                                  return 
                            }
                        }
                    }
                })
1

There are 1 answers

0
Shourob Datta On

I was facing a similar problem, My code is okay. In such case, HealthKit does not allow all data to be deleted. Only you can delete the data which are saved from your app.