I'm trying to get the underlying heart beat data from healthStore based on this conference at the WWDC 2019 - Exploring new Data Representations in HealthKit. At mark 24:40 is explained how HealthKit has a sensor capable of storing the exact timestamps of the beats and this data is accessible through the HKHeartbeatSeriesSample type.
I've created this query to retrieve that data:
But it only works if I use no predicate, which then shows all heartbeat data stored previously, but during the time period nothing is stored. I've managed to store some data using the HKHeartbeatSeriesBuilder the following way:
It stored the data and not the actual beats read by the Apple Watch device. Since I would need the actual beats to store them this way, then there must be a query that gives me that data before I have to store it in the first place (classic chicken and the egg).
How can I read the exact heart beats with timestamps during a given period of time?
I've created this query to retrieve that data:
Code Block swift func queryData(start: Date, end: Date) { let predicate = HKQuery.predicateForSamples(withStart: start, end: end, options: []) let heartBeatSeriesSample = HKSampleQuery(sampleType: HKSeriesType.heartbeat(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: nil) { (query, results, error) in guard let samples = results, let sample = samples.first as? HKHeartbeatSeriesSample else { print("Failed: no samples collected") return } print(results as Any) let heartBeatSeriesQuery = HKHeartbeatSeriesQuery(heartbeatSeries: sample) { (query, timeSinceSeriesStart, precededByGap, done, error) in guard error == nil else { print("Failed querying the raw heartbeat data: \(String(describing: error))") return } print(timeSinceSeriesStart) } self.healthStore?.execute(heartBeatSeriesQuery) } healthStore?.execute(heartBeatSeriesSample) }
But it only works if I use no predicate, which then shows all heartbeat data stored previously, but during the time period nothing is stored. I've managed to store some data using the HKHeartbeatSeriesBuilder the following way:
Code Block swift let builder = HKHeartbeatSeriesBuilder( healthStore: self.healthStore!, device: .local(), start: start ) builder.addHeartbeatWithTimeInterval(sinceSeriesStartDate: 0.5, precededByGap: false) { (success, error) in guard success else { fatalError("Could not add heartbeat: \(String(describing: error))") } }
It stored the data and not the actual beats read by the Apple Watch device. Since I would need the actual beats to store them this way, then there must be a query that gives me that data before I have to store it in the first place (classic chicken and the egg).
How can I read the exact heart beats with timestamps during a given period of time?