jjatie
jjatie

Reputation: 5332

How to make UI reflect HealthKit

I am experimenting with HealthKit for a future project, and am currently implementing a single view calorie counter. A simple text field to input a calorie amount and progress indicator which shows calories/daily allotment. There is no data model (other than calorieGoal in NSUserDefaults) as it is built entirely on top of HealthKit.

The progress indicator should be persistent between launches and reset daily, but I am having difficulty doing this in an efficient manner. The two solutions I have come up with are:

  1. fetch Dietary Calories from HealthKit every time the view is loaded. This seems to be costly for a simple task, but I am leaning towards it.
  2. create another NSUserDefualts entry to keep track of the number of calories and the date the last entry was made, then check the date every time the view is loaded/app is launched.

I feel like there should be a better solution, but I am unable to come up with one.

Upvotes: 0

Views: 168

Answers (1)

Gerd Castan
Gerd Castan

Reputation: 6849

Have a data model in memory. Your model contains the variables that hold your data.

Your model also is responsible for the code that deals with the data. This includes the code that interacts with HealthKit.

Your model knows nothing about your UI. It does not import any UI related modules. It could probably run on iPhone and watches.

Since you get your data asynchronously, your model sends a notification, when it received new data.

Your UI code listens for notifications when there is new data. When your UI gets such a notification, it redisplays the model data in the main queue.

This approach works for your simple case up to very complex apps.

Usage example for the startup case:

  • start your app
  • tell your model it should asynchronously fetch the data from hk.
  • your model also handles authorisation (makes your UI code simpler).
  • when the model finally asynchonously received the data from HealthKit, it sends the notification.
  • when your UI receives the notification, it redisplays the data from your model.

This aporoach also handles the case, when hk data is changed while your app runs (changed by another app or measured by the watch).

Upvotes: 1

Related Questions