After a full day of testing, I can confirm that HealthKit
background delivery does work in all of the following application states:
- background: in background and executing code,
- suspended: in background and not executing code,
- terminated: force-killed by the user or purged by the system.
Keep in mind: part 1
Some HealthKit
data types have a minimum update frequency of HKUpdateFrequencyHourly
. That said, even if you set up a background delivery with frequency HKUpdateFrequencyImmediate
, you won’t get updates more often than every hour or so.
Unfortunately, there is no info in the documentation about minimum frequencies per data type, but my experience with Fitness types
was as follows:
- Active Energy: hourly,
- Cycling Distance: immediate,
- Flights Climbed: immediate,
- NikeFuel: immediate,
- Steps: hourly,
- Walking + Running Distance: hourly,
- Workouts: immediate.
Note: immediate
DOES NOT mean real-time but rather “some time shortly after” the activity data samples have been written to the HealthKit
database/store.
Keep in mind: part 2
If the device is locked with a passcode, none of your background delivery observers will be called. This is intentional, due to privacy.
That said, as soon as a device is unlocked, your HealthKit
background delivery observers will be called, given that the minimum frequency time has passed.
Sample code
Take a look at Viktor Sigler’s answer, but you can skip all three steps from the beginning of his answer since they are not required for HealthKit
background delivery to work.