如何使用 Swift 查询 Healthkit 的平均心率
Posted
技术标签:
【中文标题】如何使用 Swift 查询 Healthkit 的平均心率【英文标题】:How to query Healthkit for average heart rate with Swift 【发布时间】:2016-07-22 06:59:07 【问题描述】:我需要使用 Swift 2.2 查询 HKStatistics 的平均心率。我从研究中了解到我需要的参数是 HKStatisticsOptionDiscreteAverage
我有锻炼课程的代码。如何将函数添加到以下测量心率的代码中,以使用 HKStatisticsOptionDiscreteAverage 返回锻炼会话的心率平均值?
func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery?
// adding predicate will not work
// let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None)
guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else return nil
let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: nil, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in
guard let newAnchor = newAnchor else return
self.anchor = newAnchor
self.updateHeartRate(sampleObjects)
heartRateQuery.updateHandler = (query, samples, deleteObjects, newAnchor, error) -> Void in
self.anchor = newAnchor!
self.updateHeartRate(samples)
return heartRateQuery
func updateHeartRate(samples: [HKSample]?)
guard let heartRateSamples = samples as? [HKQuantitySample] else return
dispatch_async(dispatch_get_main_queue())
guard let sample = heartRateSamples.first elsereturn
let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
self.label.setText(String(UInt16(value)))
// retrieve source from sample
let name = sample.sourceRevision.source.name
self.updateDeviceName(name)
self.animateHeart()
【问题讨论】:
你解决了吗? 不,抱歉,我没有收到回复 【参考方案1】: func getAVGHeartRate()
var typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRate)
var startDate = Date() - 7 * 24 * 60 * 60 // start date is a week
var predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: HKQueryOptions.strictEndDate)
var squery = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate, options: .discreteAverage, completionHandler: (query: HKStatisticsQuery,result: HKStatistics?, error: Error?) -> Void in
DispatchQueue.main.async(execute: () -> Void in
var quantity: HKQuantity? = result?.averageQuantity()
var beats: Double? = quantity?.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
print("got: \(String(format: "%.f", beats!))")
)
)
healthStore.execute(squery)
这是 Swift 3 版本:)
【讨论】:
【参考方案2】:这是获取平均心脏 BPM 的 Objective-c 示例:
HKQuantityType *typeHeart =[HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierHeartRate];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startDate endDate:endDate options:HKQueryOptionStrictStartDate];
HKStatisticsQuery *squery = [[HKStatisticsQuery alloc] initWithQuantityType:typeHeart quantitySamplePredicate:predicate options:HKStatisticsOptionDiscreteAverage completionHandler:^(HKStatisticsQuery *query, HKStatistics *result, NSError *error)
dispatch_async(dispatch_get_main_queue(), ^
HKQuantity *quantity = result.averageQuantity;
double beats = [quantity doubleValueForUnit:[[HKUnit countUnit] unitDividedByUnit:[HKUnit minuteUnit]]];
NSLog(@"got: %@", [NSString stringWithFormat:@"%.f",beats]) ;
);
];
[self.healthStore executeQuery:squery];
【讨论】:
以上是关于如何使用 Swift 查询 Healthkit 的平均心率的主要内容,如果未能解决你的问题,请参考以下文章
如何在 swift 中使用 HealthKit 获得步行和跑步距离
如何使用 Swift 在 healthkit 中访问锻炼的元数据
如何使用 Swift 在 iOS 中显示从 HealthKit 中检索到的 HKDocumentSample?
如何使用 Swift 从 iOS HealthKit 应用程序读取心率?