I am using the function below to get heartRateVariabilitySDNN, but its get only once and not calculate realtime like heartbeat does?
func HRVstart() {
guard let quantityType = HKObjectType.quantityType(forIdentifier: .heartRateVariabilitySDNN) else { return }
self.healthStore.execute(self.HRVStreamingQuery())
// Create query to receive continiuous heart rate samples.
let datePredicate = HKQuery.predicateForSamples(withStart: Date(), end: nil, options: .strictStartDate)
let devicePredicate = HKQuery.predicateForObjects(from: [HKDevice.local()])
let queryPredicate = NSCompoundPredicate(andPredicateWithSubpredicates:[datePredicate, devicePredicate])
let updateHandler: HKQueryUpdateHandler = { [weak self] query, samples, deletedObjects, queryAnchor, error in
if let quantitySamples = samples as? [HKQuantitySample] {
self?.HRVprocess(samples: quantitySamples)
}
}
let query = HKAnchoredObjectQuery(type: quantityType,
predicate: queryPredicate,
anchor: nil,
limit: HKObjectQueryNoLimit,
resultsHandler: updateHandler)
query.updateHandler = updateHandler
// Execute the heart rate query.
healthStore.execute(query)
// Remember all active Queries to stop them later.
self.HRVactiveQueries.append(query)
}
private func HRVStreamingQuery() -> HKQuery {
let predicate = HKQuery.predicateForSamples(withStart: NSDate() as Date, end: nil, options: .strictStartDate)
let query = HKAnchoredObjectQuery(type: self.heartRateVaribalityType, predicate: nil, anchor: nil, limit: Int(HKObjectQueryNoLimit)) {
(query, samples, deletedObjects, anchor, error) -> Void in
self.HRVformatSamples(samples: samples)
}
query.updateHandler = { (query, samples, deletedObjects, anchor, error) -> Void in
self.HRVformatSamples(samples: samples)
}
self.HRVactiveQueries.append(query)
return query
}
private func HRVformatSamples(samples: [HKSample]?) {
guard let samples = samples as? [HKQuantitySample] else { return }
guard let quantity = samples.last?.quantity else { return }
let beats = quantity.doubleValue(for: HKUnit.secondUnit(with: .milli))
let timestamp = samples[0].endDate
let newHeartRateVariablity = HeartRateVariablity(timestamp: timestamp, hrv: beats)
delegate?.heartRateVariablity(didChangeTo: newHeartRateVariablity)
print("HeartRateVariablity: \(beats)")
}