9

I need to query HKStatistics for average heart rate, with Swift 2.2. I've learned from research the parameter I need is HKStatisticsOptionDiscreteAverage

I have code for the workout session. How can I add the function to this code below measuring heart-rate to return the heart rate average of the workout session with 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()
    }
}
2
  • did you solve this?
    – MagicFlow
    Oct 23, 2016 at 19:37
  • no sorry i got no replies
    – Dimitri T
    Oct 24, 2016 at 1:13

2 Answers 2

13
    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)
}

This is the Swift 3 version :)

1

this is objective-c example of getting the average heart BPM:

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];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.