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:
Set up your project for HealthKit support in Xcode's Capabilities pane (part of your app target settings).
Check for HealthKit availability on the device (
HKHealthStore.isHealthDataAvailable()
) and create anHKHealthStore
object.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)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 otherHKQuery
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
Changing the Status Bar Text Color in Splash Screen iOS 7
How to Apply Filter to Video Real-Time Using Swift
How to Implement "Share Button" in Swift
Read a Text File Line by Line in Swift
How to Get Visible Viewcontroller from App Delegate When Using Storyboard
How to Add My App to the Share Sheet Action
iOS 11 Large Navigation Bar Title Unexpected Velocity
iOS 4.3 Hide Status Bar Permanently
Add Nsurlconnection Loading Process on Uiprogressview
Left-Align Image and Center Text on Uibutton
How to Stop Firebase from Logging Status Updates When App Is Launched
How to Define the Size of a Collectionview on Rotate
How to Disable Caching from Nsurlsessiontask
Determine Mime Type from Nsdata
Sudzc Arc Version - Objc_Msgsend Call Causes Exc_Bad_Access Using 64-Bit Architecture
Setting Maximum Number of Characters of 'Uitextview ' and 'Uitextfield '