iOS Get Heart Rate from Apple Watch in Near Real Time

Real time heart beat data from Apple Watch using HKHeartbeatSeriesSample

There isn't a way to record heart rate more precisely than you have already observed using the workout session API. Samples of the HKSeriesType.heartbeat() type are recorded when Apple Watch computes heart rate variability (see the sample type heartRateVariabilitySDNN). HRV is computed periodically in the background by Apple Watch. There is no API for initiating an HRV reading.

How to get Heart Rate Data near by Real Time from Health Kit in iOS?

Here is my own analysis regarding get nearby real-time Heart Rate.

1. If you are accessing Health Kit data using iPhone app, In this scenario, Health Kit DB NOT frequently updated/refreshed. So, your app not able to get real-time latest updated data through iPhone app.

2. Using a watch app, you can access near real-time data through Health Kit DB. Watch app is able to get the real-time latest updated Health Kit Data.

3. You need to transfer data from watch to iPhone app. Here is a code for your reference. You can write code as per your requirement. You just need to access Heart Rate through HKQuery

let defaultSession = WCSession.default

let healthStore = HKHealthStore()

var currentHeartRateSample : [HKSample]?

var currentHeartLastSample : HKSample?

var currentHeartRateBPM = Double()

//Get Heart Rate from Health Kit

func getCurrentHeartRateData(){

let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: Date())
let startDate : Date = calendar.date(from: components)!
let endDate : Date = calendar.date(byAdding: Calendar.Component.day, value: 1, to: startDate as Date)!

let sampleType : HKSampleType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)!
let predicate : NSPredicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: [])
let anchor: HKQueryAnchor = HKQueryAnchor(fromValue: 0)

let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: predicate, anchor: anchor, limit: HKObjectQueryNoLimit) { (query, samples, deletedObjects, anchor, error ) in

if samples != nil {

self.collectCurrentHeartRateSample(currentSampleTyple: samples!, deleted: deletedObjects!)

}

}

anchoredQuery.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
self.collectCurrentHeartRateSample(currentSampleTyple: samples!, deleted: deletedObjects!)
}

self.healthStore.execute(anchoredQuery)

}

//Retrived necessary parameter from HK Sample
func collectCurrentHeartRateSample(currentSampleTyple : [HKSample]?, deleted : [HKDeletedObject]?){

self.currentHeartRateSample = currentSampleTyple

//Get Last Sample of Heart Rate
self.currentHeartLastSample = self.currentHeartRateSample?.last

if self.currentHeartLastSample != nil {

let lastHeartRateSample = self.currentHeartLastSample as! HKQuantitySample

self.currentHeartRateBPM = lastHeartRateSample.quantity.doubleValue(for: HKUnit(from: "count/min"))
let heartRateStartDate = lastHeartRateSample.startDate
let heartRateEndDate = lastHeartRateSample.endDate

//Send Heart Rate Data Using Send Messge

DispatchQueue.main.async {

let message = [
"HeartRateBPM" : "\(self.currentHeartRateBPM)",
"HeartRateStartDate" : "\(heartRateStartDate)",
"HeartRateEndDate" : "\(heartRateEndDate)"
]

//Transfer data from watch to iPhone
self.defaultSession.sendMessage(message, replyHandler:nil, errorHandler: { (error) in
print("Error in send message : \(error)")
})

}

}

}

Read Heart Rate in Apple Watch Series 3 without creating an app on the Watch

Apple Watch syncs all of its recorded heart rate data (automatically sampled every five minutes while wearing, and more frequently during workout sessions) to the HealthKit store on the companion iPhone.

So you can create an iOS app that (with the user's permission) reads the stored heart rate data using HealthKit. The gist of it:

  1. Set up your project for HealthKit support in Xcode's Capabilities pane (part of your app target settings).

  2. Check for HealthKit availability on the device (HKHealthStore.isHealthDataAvailable()) and create an HKHealthStore object.

  3. Verify that you have user permission to access heart rate data:

    let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate)!
    healthStore.requestAuthorization(toShare: nil, read: [heartRateType], completion: myHandler)
  4. After that completion handler reports success, use HKSampleQuery to search for the most recent heart rate sample, a set of heart rate samples within a specified time frame, etc. (Or other HKQuery subclasses for things like average heart rate over time, etc.)


If instead what you're asking is for a way to read the user's current heart rate "right now" from an iOS app, without creating a companion watchOS app... no, there's not a way to do that.

Get heart rate information from Apple watch to paired iPhone

1. There is no open API for developers for getting data from heart-rate sensor. Apple uses their private methods for doing this.

2. Your idea about getting this data already from HealthKit is not good:

  • Information can be outdated.
  • As I know, user can select if he wants to track his heart rate or
    not. And you have no ability to check if this information is
    tracked.

So, currently, there is no suitable options for making heart tracking app.


UPDATE (2015-06-09)

On the WWDC15 Apple announced watchOS 2.

In this update there will be realtime access to the heart rate sensor and other sensors!
More info is here: https://developer.apple.com/watchos/pre-release/



Related Topics



Leave a reply



Submit