toast
toast

Reputation: 1980

Best approach to reading workout data from HealthKit

I'm wanting to upload a workout's heart rate information to my server. The problems is, I'm not sure how to get this information.

When I end the workout, I save the heart rate, and energy burned info. I could include other code here that also writes this information to Core Data, then basically immediately pulls it out and syncs it with the iOS app, which syncs it with the server. Is this the best approach?

In iOS is it possible to query HealthKit workout sessions, and extract a list of heart rate readings at each update?

Not really relevant, but for some clarification around the immediate sync I noted above. It wouldn't always sync it with the server immediately, as when the Watch is out of range, the user could create other workout sessions, which have related data stored in Core Data, and then synced all at once when back in range.

Upvotes: 2

Views: 1883

Answers (1)

Vladimir Kaltyrin
Vladimir Kaltyrin

Reputation: 631

When I end the workout, I save the heart rate, and energy burned info. I could include other code here that also writes this information to Core Data, then basically immediately pulls it out and syncs it with the iOS app, which syncs it with the server. Is this the best approach?

I would suggest to create some HealthKitService which responsibility will be to fetch and save data to HKHealthStorage. Use a PONSO object to describe the DTO you're going to pass within different layers of your app.

It will look something like this:

struct Workout {
    let date: Date
    let sets: Double
    let reps: Double
    let heartRate: Double
}

protocol HealthKitService: class {
    func saveWorkout(_ workout: Workout, completion: (() -> ())?)
    func fetchWorkouts(by date: Date, completion: (([Workout]) -> ())?)
}

For simplicity I'd recommend not to using Core Data if your data model is not different from HKWorkout, but if you need to persist some additional data associated with workout which is not supported by HealthKit then you have to setup an own storage.

If you would like to send a user's health data to your own server, please check the Protecting User Privacy document to prevent rejection of your app during App Store Review.

In iOS is it possible to query HealthKit workout sessions, and extract a list of heart rate readings at each update?

Yes, it's possible. Check the official documentation for HKWorkout. Basically you need a HKHealthStorage to save an associated with HKWorkout heart rate as a HKSample. Then you can execute query to receive the data, here is a reference.

Upvotes: 3

Related Questions