I'm trying to get the time of each heart beat from an Apple Watch. Currently I am able to get the heart rate in beats per minute but can't get the times of each individual heart beat. It seems to send the heart rate data at random time intervals making it not possible to use the time of each sample to get heart beat times.
It doesn't matter what the units are as long as I can get it to update when it receives a new beat rather than every few beats as it is currently doing. Or if I can get it to give me the time of each beat rather than beats per time. Is there someway to force updateHandler to be called when a heart beat comes in? I thought that was the point of using the HKAnchoredObjectQuery. Or is there some other method to get the beat data?
func startRecordingHeartRate() {
let heartRateSample = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let datePredicate = HKQuery.predicateForSamples(withStart: Date(), end: nil,
options: .strictStartDate)
let anchor: HKQueryAnchor? = nil
let updateHandler: (HKAnchoredObjectQuery, [HKSample]?, [HKDeletedObject]?, HKQueryAnchor?, Error?) -> () = {
query, newResult, deleted, newAnchor, error in
if let samples = newResult as? [HKQuantitySample] {
guard samples.count > 0 else {
return
}
for sample in samples {
let doubleSample = sample.quantity.doubleValue(for: heartRateUnit)
let timeSinceStart = sample.endDate.timeIntervalSince(self.startTime)
self.hkHeartRate[0].append(doubleSample)
self.hkHeartRate[1].append(Double(timeSinceStart))
}
self.updateHeartRateLabel()
self.processData.heartRateArray = self.hkHeartRate
self.processData.checkData()
}
}
let heartRateQuery = HKAnchoredObjectQuery(type: heartRateSample!,
predicate: datePredicate,
anchor: anchor,
limit: Int(HKObjectQueryNoLimit),
resultsHandler: updateHandler)
heartRateQuery.updateHandler = updateHandler
healthStore.execute(heartRateQuery)
}