我有锻炼课程的代码.如何在以下测量心率的代码中添加该功能,以使用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,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版:)
总结以上是内存溢出为你收集整理的如何使用Swift查询Healthkit的平均心率全部内容,希望文章能够帮你解决如何使用Swift查询Healthkit的平均心率所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)