Search code examples
swiftapple-watchhealthkit

Swift HealthKit Trigger Heart Rate Sample


I'm able to read average heart rate data from HealthKit for a period of time (duration of workout) with the below code.

However, when I look in the Apple Health app, it shows that the heart rate samples from the Apple Watch are taken very infrequently (every 15-30 min). This makes my average HR read for the period quite inaccurate.

How can I trigger HealthKit to sample (gather) Heart Rate data from the watch and write it to HealthKit?

    let endDate = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.minute, value: duration, to: startDate, options: NSCalendar.Options())
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions())

    let squery = HKStatisticsQuery(quantityType: heartRateType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.discreteAverage, completionHandler: { (qurt, result, errval) -> Void in

        guard errval == nil else { print("error"); completion(0.0, errval); return }

        var averageHeartRate : Double = 0.0
        if (result != nil && result!.averageQuantity() != nil) {
            let quantity : HKQuantity = result!.averageQuantity()!
            averageHeartRate = quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
        }
    })

Solution

  • To get more frequent heart rate data from Apple Watch, the user must be running an app on their watch that is tracking an HKWorkoutSession. If your app has a paired watchOS app that tracks workouts, you can start a workout from the iPhone by using startWatchApp(with workoutConfiguration:completion:).