ngrunks
ngrunks

Reputation: 11

How to get heart rate data from HealthKit for each workout

I am attempting to retrieve heart rate for all workouts completed and also start and stop times for the workout and return all values as Times or Quantity items in my JSON result. I have been able to get all workouts by querying for duration greater than 0, but now I would like to get this additional info.

        let workoutPredicate = HKQuery.predicateForWorkouts(with: .greaterThanOrEqualTo, duration: 1)

        let compound = NSCompoundPredicate(andPredicateWithSubpredicates:
            [workoutPredicate])

        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate,
                                              ascending: true)

        let query = HKSampleQuery(
            sampleType: .workoutType(),
            predicate: compound,
            limit: 0,
            sortDescriptors: [sortDescriptor]) { query, samples, error in
                DispatchQueue.main.async {
                    guard let finalSamples = samples as? [HKWorkout] else {
                        result()
                        return
                    }
                    result(finalSamples.map { sample -> NSDictionary in
                        return ["duration" : sample.duration, "totalDistance": sample.totalDistance?.doubleValue(for: HKUnit.mile()) as Any, "totalEnergyBurned": sample.totalEnergyBurned?.doubleValue(for: HKUnit.kilocalorie()) as Any]
                    })
                }
        }
        HKHealthStore().execute(query)

I would like to get the heart rate data for the workout and workout start/end time.

Upvotes: 1

Views: 875

Answers (1)

Gerard
Gerard

Reputation: 2357

A little late but start & end date/time per workout should be easy with:

print("started @: \(sample.startDate), ended @: \(sample.endDate)")

Did you manage to get heart rates (min/max/avg) per workout? I am also interested to get this & can't seem to figure out if this is possible or not?

Upvotes: -3

Related Questions