HealthKit: Real-Time Sleep Tracking with Heart Rate Data

I am trying to track a user's real-time sleep state using heart rate data, but I have encountered several issues:

When using HKSampleQuery on the phone to fetch heart rate data, I can only retrieve data recorded before the app comes to the foreground or before it is terminated and restarted (see related issue: https://developer.apple.com/forums/thread/774953).

I attempted to get data on the Apple Watch and send updates to the phone via Watch Connectivity. However, if I use WKExtendedRuntimeSession, although I can obtain data on the watch, once the watch screen goes off, it can no longer transmit data via Watch Connectivity to the phone (since I cannot guarantee the app will remain in the foreground when lying in bed).

On the other hand, using HKWorkoutSession results in interference with the activity rings and causes the heart rate sensor to run too frequently, which I worry may affect the battery life of the watch.

Is there an elegant solution for tracking a user's heart rate data for sleep monitoring?

An watchOS app can't continuously run in the foreground for ever, as discussed in the following post:

In your case, I have the following theory:

  1. Use HKObserverQuery + enableBackgroundDelivery(for:frequency:withCompletion:) to observe the change of the Health data. With that, if the observed data in the HealthKit store is changed, your app will be woken up (if it is suspended), and the updateHandler of the query will be called.

  2. In the updateHandler of the query, fetch the changed data, and send the data to your iOS companion app.

The system allows a short period of time to run the updateHandler after waking up your app, and I hope that is long enough for you to send the data via Watch Connectivity.

I haven't really verified my theory with a real app, and so it will be great if you don't mind to give it a try and share what you get here.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

HealthKit: Real-Time Sleep Tracking with Heart Rate Data
 
 
Q