Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query Healthkit for average heart rate with Swift

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()
    }
}
like image 305
Dimitri T Avatar asked Jul 22 '16 06:07

Dimitri T


People also ask

How do I get heart rate data from HealthKit?

Step 1: Import the HealthKit framework. That gives me access to HealthKit symbols that “are declared outside the current file.” Step 2: Create a member property to store an instance of HKHealthStore, the “access point for all data managed by HealthKit.” Step 3: Create member properties that we’ll use to ask HealthKit about heart rate data.

Does Swift 4 work with HealthKit?

Walk you through some Swift 4 code I wrote for reading from and writing to the HealthKit data store. Show you the output from my code as it works with health data. And, finally, give some hints as where you can go next with HealthKit. Please follow and read the hyperlinks I’ve included throughout the article.

What is HealthKit for iOS?

Update Note: This tutorial has been updated for Swift 4, Xcode 9 and iOS 11 by Ted Bendixson. The original tutorial was written by Ernesto García. HealthKit is an API that was introduced in iOS 8. It acts as a central repository for all health-related data, letting users build a biological profile and store workouts.

Can other apps read data from Apple’s HealthKit?

Other data, like a user’s heart rate and blood pressure, can be collected and written into the HealthKit by developers — and they can read that data, too. In fact, once an app stores data in HealthKit, that data is available to all other apps, but only if the user consents on an app-by-app and health-data-point-by-data-point basis.


2 Answers

    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 :)

like image 71
marcomoreira92 Avatar answered Dec 04 '22 08:12

marcomoreira92


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];
like image 43
MagicFlow Avatar answered Dec 04 '22 08:12

MagicFlow