我需要使用 Swift 2.2查询HKStatistics的平均心率.我从研究中学到了我需要的参数是HKStatisticsOptionDiscreteAverage 我有锻炼课程的代码.如何在以下测量心率的代码中添加该功能,以使用HKStatisti
我有锻炼课程的代码.如何在以下测量心率的代码中添加该功能,以使用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 else{return} 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() } }
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版:)