我写了一个从HKHealthStore
检索最大心率和平均心率的函数。虽然两个HKStatisticQuery()
调用都有效,但由于完成处理程序是异步的,因此函数的返回值(maxHRT,avgHRT)为(0,0)。
在更新返回值和退出函数之前,等待两个完成处理程序返回的优雅方法是什么?
代码:
func calcHeartRateStatistics() -> (Double, Double){
var maxHRT:Double = 0
var avgHRT:Double = 0
// First specify type of sample we need, i.e. Heart Rate Type
//
let sampleType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
// Create query predicate so result only returns objects within the period between Start Date
// and End Date
//
let predicate = HKQuery.predicateForSamplesWithStartDate(pvtStartDate, endDate: pvtEndDate, options: .None)
// Query for Maximum Heart Rate that occurred between Start Date and End Date
//
let queryMaxHeartRate = HKStatisticsQuery(quantityType: sampleType!,
quantitySamplePredicate: predicate,
options: .DiscreteMax)
{ [unowned self] (query, result, error) in
if let maxQuantity = result?.maximumQuantity() {
let maxHeartRate = maxQuantity.doubleValueForUnit(HKUnit(fromString: "count/min"))
maxHRT = round(maxHeartRate)
}
}
// Query for Average Heart Rate that occurred between Start Date and End Date
//
let queryAverageHeartRate = HKStatisticsQuery(quantityType: sampleType!,
quantitySamplePredicate: predicate,
options: .DiscreteAverage)
{ [unowned self] (query, result, error) in
if let averageQuantity = result?.averageQuantity(){
let avgHeartRate = averageQuantity.doubleValueForUnit(HKUnit(fromString: "count/min"))
avgHRT = round(avgHeartRate)
}
}
pvtHealthStore.executeQuery(queryMaxHeartRate)
pvtHealthStore.executeQuery(queryAverageHeartRate)
return (maxHRT, avgHRT)
} // calcHeartRateStatistics