我下面的心率查询使用较旧的传统HKSampleQuery
来获取心率,但是,如果应用程序将心率保存到 Apple Health 中,HKCumulativeQuantitySample
那么我下面的查询不会捕获HKCumulativeQuantitySample
. 如何查询以便在 Apple Health 中捕获这两种类型的心率样本?
class func getHeartRateSamplesFrom(workout: HKWorkout, handler: @escaping ([HKQuantitySample]?, WorkoutManagerError?) -> Void) {
guard let heartRateType:HKQuantityType = HKQuantityType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate) else { return }
//predicate
let startDate = workout.startDate
let endDate = workout.endDate
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: .strictStartDate)
//descriptor
let sortDescriptors = [
NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
]
let heartRateQuery = HKSampleQuery(sampleType: heartRateType,
predicate: predicate,
limit: (HKObjectQueryNoLimit),
sortDescriptors: sortDescriptors)
{ (query:HKSampleQuery, results:[HKSample]?, error:Error?) -> Void in
guard error == nil else { print("get heart rate error"); return }
guard let unwrappedResults = results as? [HKQuantitySample] else { print("get heart rate error"); return}
handler(unwrappedResults, nil)
}
HealthStoreSingleton.sharedInstance.healthStore.execute(heartRateQuery)
}