How to automate deleting duplicate HealthKit entries?

Some Apps I have been using to track sleep (for example Sleep++ and AutoSleep) have been saving duplicate entries in HealthKit (sometimes even storing 4 or 5 duplicates), almost every day (for a very long period). I would like to remove those duplicates.

Deleting these duplicates manually will be an enormous chore (and with a high risk of accidentally deleting a unique record); thus I want to automate this. But how?

I’m familiar with these tools/languages:

  • Xcode (Swift, Objective-C)
  • Pythonista (Python)
  • Scriptable (JavaScript)
  • Shortcuts

But I’m afraid it might not possible at all:

Your app can delete only those objects that it has previously saved to the HealthKit store.

Source: Apple

(How) Can I do this?

I wrote some Swift code to fetch all sleep data.

It returned 15,342 entries of which only 10,557 are unique…

So almost 5K of duplicate entries?! :cry: