Healthkit background delivery when app is not running

TechSeeker picture TechSeeker · Oct 15, 2014 · Viewed 15.5k times · Source

Can HealthKit background delivery launch the application if is not running? Particularly in a terminated state?

Answer

damirstuhec picture damirstuhec · Jan 29, 2016

After a full day of testing (iOS 9.2) 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 but 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 documentation about minimum frequencies per data types, 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 has been written to the HealthKit database/store.

Keep in mind: part 2

If the device is locked with a passcode, none of you background delivery observers will be called. This is intentional due to the privacy concerns (read more: https://developer.apple.com/library/ios/documentation/HealthKit/Reference/HealthKit_Framework/).

That said, as soon as the user unlocks the device, your HealthKit background delivery observers will be called (if the minimum frequency time has passed, of course).

Sample code:

Take a look at Viktor Sigler's answer. Although, you can skip all three steps from the beginning of his answer since they are not required for HealthKit background delivery to work.