Reputation: 159
I'm trying to get the instance 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 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.
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)
}
func updateHeartRateLabel() {
let endIndex = self.hkHeartRate[0].endIndex
let lastHeartRate = self.hkHeartRate[0][endIndex-1]
self.heartRateLabel.setText(self.numberFormatter.string(from:NSNumber(value: lastHeartRate)) ?? "")
}
Upvotes: 0
Views: 718
Reputation: 7343
There is no way to observe individual heart beat events on Apple Watch. The averaged heart rate quantity samples are the only representation of heart rate available to you. If you want to increase the frequency of heart rate measurements, your app should start an HKWorkoutSession
.
Upvotes: 1