I follow the sample code of Apple Doc to get the ECG with success. Now I want to get the users average heart rate during the ECG. I have the following code :
var ecgSamples = [(Double,Double)] ()
let predicate = HKQuery.predicateForSamples(withStart: Date.distantPast,end: Date.distantFuture,options: .strictEndDate)
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let ecgQuery = HKSampleQuery(sampleType: HKObjectType.electrocardiogramType(), predicate: predicate, limit: HKObjectQueryNoLimit, sortDescriptors: [sortDescriptor]){ (query, samples, error) in
guard let samples = samples else {
return
}
let query = HKElectrocardiogramQuery(samples[counter] as! HKElectrocardiogram) { (query, result) in
switch result {
case .error(let error):
print("error: ", error)
case .measurement(let value):
let sample = (value.quantity(for: .appleWatchSimilarToLeadI)!.doubleValue(for: HKUnit.volt()) , value.timeSinceSampleStart)
print(sample)
ecgSamples.append(sample)
case .done:
print("done")
DispatchQueue.main.async {
completion(ecgSamples,samples[counter].startDate)
}
}
}
self.healthStore.execute(query)
}
self.healthStore.execute(ecgQuery)
I don't understand how to pick the average heart rate ?
CodePudding user response:
You can get it from HKElectrocardiogram
object:
let electrocardiogram = samples[counter] as! HKElectrocardiogram
let averageHeartRate = electrocardiogram.averageHeartRate?.doubleValue(for: HKUnit.count().unitDivided(by: .minute())) ?? 0