iOS get heart rate from Apple Watch in near real time - ios

I need to make an app that records heart rate data in near real time and send this data to a server as soon as possible.
First I took this approach: Watch os 2.0 beta: access heart beat rate
In fact it is working fine. There is new heart rate data in the HealthKit every five seconds. But now I have the problem that I can't sync that with a server.
My first approach was the Watch app. The watch was sending data to a server. That doesn't work because as soon as the screen turns black on the watch, it stops sending.
My next approach was to query the HealthKit on the iPhone every five seconds for new data. This works, as long as the app is in foreground.
Then I saw that there's some kind of background functionality that watches the HealthKit itself and revokes the app from background and you can do something.(enableBackgroundDeliveryForType) This doesn't seem to work for heart rate (the Apple Documentation says for things like steps this doesn't work, I guess heart rate is one of those).
I'm stuck now. Do you know how to it? I would need some background task that is executed every 5-10 seconds on the iPhone. That seems to be impossible

UPDATE
As noticed by #BootMaker, Apple made background mode available for HKWorkout apps in WatchOS 3, so it's working now. You have to run a HKWorkoutSession and this will keep your heartrate delivery in real time even when the app is in the background (dark screen on watch)
The closest you are going to be is while the watch app is open.
Why I'm stating this?
There are two HealthKit's Database (one at the iPhone and another at the Apple Watch). When they sync is arbitrary and decided only by the O.S.
The closest you are going to be to real time is when you don't have any password locking your screen in iPhone or Apple Watch.
Either way, there's no guarantee that the sync will happen every time a new measure is added to Apple Watch's HealthKit
The only way to force the Heart rate sensor into working in real time is via workouts or observer while your Apple Watch app is in FOREGROUND.
Background delivery is NOT available for Apple Watch apps.
Watch OS 2 request the sensor to measure automatically (in background) every 10 minutes minimum.
There's no other workaround, if you need real time for longer periods, or while the user is not using your app, you will need to use an specialized wearable.

If anyone still need to get heart rate or other data in real time. Use this solution:
Develop an apple watch app/extention
In watch app, using HKHealthStore, HKWorkoutConfiguration, HKWorkoutSession, HKLiveWorkoutBuilder to create an Workout. After create workout, your watch app will get heart rate in real time.
Using watch kit connection with WCSession to send data to iPhone app.
Enable background mode both in apple watch and iPhone.
I tested, even app terminated, we can still get heart rate (I used Local notification for posting heart rate data for debugging)

Related

Unable to read real time data from HealthKit when App is in foreground

We are to trying to fetch data from Health kit on Specific Interval of time. One first attempt we are able to fetch data from HealthKit and It shows last collected samples.
After first attempt, We measured Heart rate from Watch, So It should be synchronised with HealthKit .
But now we are making second attempt from mobile to read latest added sample from Health kit, But it is returning what we had on first attempt, not the last one which we measured from Watch.
Once we put our Mobile app in background for even a second and open it again, Then health kit provides the latest reading (taken from watch).
It seems Health kit is not being Synchronised while our app (3rd party app) is running in Foreground.
In short we want to track Live Heart rate (also other data) whole Day (24 * 7) taken by watch and send to Mobile App so it can sync with our server.
Can please anyone help with this ? Any kind of solution to get over this stuff. Thank you in advance.
We already tried
Get live heart rate from Watch by HKWorkoutSession and send it to Mobile App via WCConnection. But WCSession becomes unreachable when Watch screen becomes dark. so we are unable to send data to watch.
We tried HKObserverQuery, But when app goes into background it stops running after 30 seconds of entering in background or after giving 3 or 4 results.
We tried HKSampleQuery in Timer to fire after every 5 seconds. And we got this use case as described problem.

How to get real time Health updates from Apple watch, sync it with health kit and send it to server?

I am working on a iPhone application that consumes health kit data and sends the data to Server whenever i open the iPhone app.
My requirement is whenever there is any change in heart rate, step count etc. from apple Watch(even when watch is locked - black screen), the health kit in iPhone should be updated and the same should be sent to my server as well even when my iPhone app is in background or device is locked. Basically i am trying to send updates to server whenever there is a change in healthkit data. Is this even possible?
I followed this link HealthKit (iOS) won't deliver data in background (objC) to implement Observer Query to fetch heart rate from health kit and it is working only when i unlock the iPhone that too in some interval. I need to invoke this handler whenever there is any updates to healthkit data in watch app even when my iPhone app is in background or phone is locked.
Healthkit background delivery when app is not running "A user experienced how to work minimum frequencies per data types."

How to avoid keeping watch app in front when using HKWorkoutSession?

I have developed an iPhone app with watch app for getting live stream of heart rate. As mentioned in many stackoverflow threads iOS get heart rate from Apple Watch in near real time, i have used HKWorkoutSession to get the updated heart rate and sending it to server (Workout session will always be active to get live stream of heart rate).
The issue here is, this application always stays in front of watch app(which is the expected behaviour when we use HKWorkoutSession). But i don't want this behaviour to happen, since the app only does the job of getting heart rate updates and sending it to server.
My app now sends the heart rate correctly to server even when the watch screen is off and when the app is in background since i have used Required background modes (Watch) in info.plist.
Is there any way that we can avoid this app being in front of watch face every-time the user opens the watch?
You cannot avoid making you app frontmost while in a workout session on watchOS. You should file a bug with Apple to request an API with the behavior you want for your app.

Real Time sensor data from the Apple Watch during a Workout Session

Assuming I start a workoutsession on the apple watch is there a way to get say accelerator, distance or energy burnt or any other data that the Apple Watch sensor supports in real time even when the watch is sleep (screen is off). If so what's the sample rate for this data being available. Can I execute any code when I receive this data in those intervals while the watch is sleep. For example can I trigger a haptic notification when I receive the data although the watch screen is still off and while in the active workout session?
Apps on watchOS 2 do not run while the screen is off, even after starting a workout session. Your app can only process data while the screen is on.

HKWorkoutSession: Not getting Heart Rate when screen is turned off in watchOS 2

I am using iOS 9 beta 4 and watchOS 2 beta 4.
I can't seem to get any heart rate data when the watch screen turns black (locks). I will get a call to applicationWillResignActive and then the heart rate data just stops.
It seems that the sensor is deactivating after some time as well (not green anymore), when the screen locks.
Anyone else seeing this behavior? I can post my code for initing the WorkoutSession if anyone else getting heart rate data when the screen on the watch is locked.
Starting in watchOS 3.0 you can add the WKBackgroundModes entry with the workout-processingvalue to the extension's Info.plist.
From the docs:
Running in the Background Workout sessions can run in the background.
Background running grants an app the following abilities:
The app continues to run throughout the entire workout session, even
when the user lowers their wrist or interacts with a different app.
When the user raises their wrist, the app reappears, letting the user
quickly and easily check their current progress and performance.
The app can continue to access data from Apple Watch’s sensors in the
background, letting you keep the app up to date at all times. For
example, a running app can continue to track the user’s heart rate,
ensuring that the most recent heart rate data is displayed whenever
the user raises their wrist.
The watch app platform is designed to totally disable your code shortly after applicationWillResignActive(). However with an HKWorkoutSession active, the watch should record heart rate data to the HK store in the background (as long as another watch app doesn't start a new one and cancel yours).
This is roughly what I do to start heart rate collection:
func startCollectingHR(){
guard workoutSession == nil else{return} // Make sure it's not already started
// Also make sure you get the appropriate HealthKit permissions
workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Outdoor)
workoutSession!.delegate = self
healthStore.startWorkoutSession(workoutSession!)
print("HR collection started.")
}
Unfortunately, I haven't found any way to get heart rate to reliably live-stream anywhere outside the HealthKit store on the watch.
I noticed similar behaviour and found that the first workout session would run as intended, but subsequent ones would only run when the watch face was active. I solved the problem by resetting HKWorkoutSession once the session was completed.

Resources