心电图期间无法获取用户的平均心率

Cant get user’s average heart rate during the ECG

我按照Apple Doc的示例代码成功获取了心电图。现在我想在心电图期间获得用户的平均心率。我有以下代码:

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)

我不明白如何选择平均心率?

你可以从HKElectrocardiogram对象中获取:

let electrocardiogram = samples[counter] as! HKElectrocardiogram
let averageHeartRate = electrocardiogram.averageHeartRate?.doubleValue(for: HKUnit.count().unitDivided(by: .minute())) ?? 0