Sleep Samples sum off by 2 minutes

Hi everyone!

I'm trying to get the total sleep time for a given day, but users report that there's a difference between what my app reports and what the Apple Health app reports. In particular, we're off by 2 minutes less on average.

What we're doing is:

  1. Get all the samples that are either core, deep, rem or unspecified
  2. Cut-off time at 3 PM previous day
  3. Merge overlapping intervals
  4. Add all the remaining intervals

For debugging purposes I'm storing and sending all the raw samples to a server, and I have run tests and I don't find anything wrong. It looks like the number we come up with is correct according to our own rules. I wonder, how is Apple adding up all the samples to arrive at a number that's slightly off to our number.

Any insight would be appreciated. Thanks.

I am not at the position to comment how Health.app does the statistics, but the way you described is about right, that is, fetching all the asleep samples and adding the duration of the samples without counting any overlaps.

The cut-off time is interesting to me though. Did you try to set up a sleep schedule, and use the schedule as the cut-off time to see if that makes any difference?

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Hi, thanks for your answer.

What do you mean by "set up a sleep schedule"? Do you mean in Apple's Health application? And then that I use that schedule for the cutoff time in my code? Because I understand we can't retrieve the schedule using HealthKit, so I guess that wouldn't work for the general case. Right?

Thanks!

Sleep Samples sum off by 2 minutes
 
 
Q