Today more and more people are opting to cut the gym out completely and get fit where and when it suits them — from the comfort of their devices. There are rising number of apps out there that complement your workout schedule as well as keep your data history to analyze your health over time.
Given jam-packed schedules, it is getting tougher for an individual to think about health on top of everything else. It might seem like a full-time job. Luckily, we are living in the 21st century, and technology is here to help. So this is high time to launch apps in the health and fitness domain.
All the relevant and necessary health data of user is available over both the platforms, Android as well as iOS. You can add value by processing that data and chipping in your novel ideas, algorithm, logic and thus providing new useful insights.
Because health data may contain sensitive, personal information, apps must receive permission from the user to read and modify data. They must also take steps to protect that data at all times.
In this post we will learn about the default Health app options Google and Apple provide within their devices, and how can you connect your Ionic 4 apps to make use of these data.
Default Fitness Packages
HealthKit, iOS
HealthKit on iPhone provides a central repository for health and fitness data on iPhone and Apple Watch. With the user’s permission, apps can communicate with the HealthKit store to access and share this data.
Creating a complete, personalized health and fitness experience includes a variety of tasks:
- Collecting and storing health and fitness data
- Analyzing and visualizing the data
- Enabling social interactions
The main dashboard for Apple Health is called Health Data and breaks down your health into four key areas: Activity, Mindfulness, Nutrition and Sleep.
HealthKit apps take a collaborative approach to building this experience. HealthKit app allows data exchange with other apps. Your app does not need to provide all of the features of HealthKit. Instead, you can focus just on the subset of tasks that most interests you.
For example, users can select their favorite weight-tracking, step-counting, and health challenge app, each calibrated to their personal needs. Because HealthKit apps freely exchange data (with user permission), the combined suite provides a more customized experience than any single app on its own. For example, when a group of friends joins a daily step-counting challenge, each person can use their preferred hardware device and app to track their steps, while everyone in the group uses the same social app for the challenge.
HealthKit is also designed to manage and merge data from multiple sources. For example, users can view and manage all of their data in the Health App, including adding data, deleting data, and changing an app’s permissions. Therefore, your app needs to handle these changes, even when they occur outside your app.
Google Fit, Google
Google Fit is a health-tracking platform developed by Google for the Android operating system. It is a single set of APIs that blends data from multiple apps and devices. Google Fit uses sensors in a user’s activity tracker or mobile device to record physical fitness activities (such as walking or cycling), which are measured against the user’s fitness goals to provide a comprehensive view of their fitness. It lets
- Users control their fitness data
- Developers build smarter apps, and
- Manufacturers focus on creating amazing devices.
Google Fit allows developers to upload fitness data to a central repository where users can access their data from different devices and apps in one location:
- Fitness apps can store data from any wearable or sensor.
- Fitness apps can access data created by other apps.
- User’s fitness data is persisted when they upgrade their fitness devices.
Since you read fitness data from Google Fit, you are also required to write the fitness data you collect to Google Fit.
Google Fit APIs are prohibited for non-fitness purposes, such as storing medical or biometric data, selling data, or using data for advertising.
Fitness plugins in Ionic 4
Now let’s see how we can use the Fitness data in Ionic 4 apps
1. Health KitPlugin
The HealthKit plugin allows you to read data from and write data to the iOS 8+ HealthKit framework. Any data saved shows up in the iOS Health app, and is available for other iOS apps.
2. Health
A plugin that abstracts fitness and health repositories like Apple HealthKit or Google Fit. This is the most extensive plugin among all available ones.
3. Pedometer
Fetch pedestrian-related pedometer data, such as step counts and other information about the distance traveled.
4. Stepcounter
Cordova plugin for using device’s stepcounter on Android (API > 19)
We’ll go in details of the Health Plugin, which is most extensive among all these plugins. All other plugins will behave in a similar way.
Ionic 4 Health Plugin
Install Plugin
To begin with, we need a basic Ionic 4 app. If you are a beginner, you can check out our blog on How to create Ionic 4 apps. Once you have a basic Ionic 4 app, import the Health plugin by
$ ionic cordova plugin add cordova-plugin-health
$ npm install @ionic-native/health
Import plugin in your page
Import the plugin in your page/ component using
import { Health } from '@ionic-native/health/ngx';
constructor(private health: Health) { }
Include plugin in app providers
Also import the plugin provider in app.module.ts
and include the plugin in providers array
import { Health } from '@ionic-native/health/ngx';
@NgModule({
...
providers: [
...,
Health,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
Check platform is ready
One important thing to note is to access the plugin only when the Platform is ready. Otherwise it will throw error of plugin not installed
or may be it won’t throw any error but just won’t work.
ngOnInit() {
this.checkPlatformReady();
}
async checkPlatformReady() {
const ready = !!await this.platform.ready();
if (ready) {
// Use plugin functions here
}
}
iOS quirks
This is a requirement in iOS only. For any app that wants to read/write private data, the app requests permission from user along with a usage description. For our Health plugin, we need read
and write
permission. These can be set in info.plist
in Xcode. Without this the app will crash in iOS when you try to run any function other than isAvailable()
Also, make sure your app id has the ‘HealthKit’ entitlement when this plugin is installed. This is added automatically to your app if you use Cordova-ios 4.3.0 or higher.
You need to have HealthKit entitlement in your app’s provisioning profile.
Methods
isAvailable()
Tells if either Google Fit or HealthKit are available.
promptInstallFit()
Checks if recent Google Play Services and Google Fit are installed. If the play services are not installed, or are obsolete, it will show a pop-up suggesting to download them.
requestAuthorization()
Requests read and write access to a set of data types. This method must be called before using the query and store methods, even if the authorization has already been given at some point in the past. Failure to do so may cause your app to crash, or in the case of Android, Google Fit may not be ready.
this.health.requestAuthorization([
'distance', 'nutrition', //read and write permissions
{
read: ['steps','height', 'weight'],//read only permission
write: ['height', 'weight'] //write only permission
}
])
.then(res => console.log("response " + res))
.catch(e => console.log("error "+e));
query()
This method gets all the data points of a certain data type within a certain time window. This is the essence of Health plugins, using this function we can read and write data from iOS Health Kit and Google Fit.
To begin with, we have some sample data in the iOS HealthKit dataset
Sample query
this.health.query({
startDate: new Date(new Date().getTime() - 10*24*60*60*1000 ),
// ten days ago
endDate: new Date(), // now
dataType: 'steps',
limit: 1000
}).then(data=>{
console.log(data);
}).catch(e => {
console.log("error "+ e);
})
On executing the above query
, you will get a result similar to the following (Assuming you have data in HealthKit)
As an example, the data from our example repo shows a 10 day data like following
queryAggregated()
Another query method, but instead of individual values, it returns a sum of values. E.g. when you want to check the steps walked in last one week etc.
this.health.queryAggregated({
startDate: new Date(new Date().getTime() - 10*24*60*60*1000 ),
// ten days ago
endDate: new Date(), // now
dataType: 'steps',
bucket: 'week'
}).then(data=>{
console.log(data);
}).catch(e => {
console.log("error "+ e);
})
As an example, the data from our example repo shows a 10 day data, grouped in weeks, like this
store()
This method can be used to store data from your Ionic 4 app to HealthKit or Google Fit
this.health.store({
startDate: new Date(new Date().getTime() - 3*60*1000 ),
// three minutes ago
endDate: new Date(), // now
dataType: 'steps',
value: 180,
sourceName: 'my_app',
sourceBundleId: 'com.example.my_app'
}).then(data=>{
console.log(data);
}).catch(e => {
console.log("error "+ e);
})
More details related to the data types, methods and quirks for the Health plugin are available on the official plugin github repo.
The official Apple documentation for HealthKit can be found here.
Also, make sure your app and AppStore description complies with these Apple review guidelines.
Differences between HealthKit and Google Fit
- HealthKit includes medical data (e.g. blood glucose), whereas Google Fit is mainly meant for fitness data (although now supports some medical data too).
- HealthKit provides a data model that is not extensible, while Google Fit allows defining custom data types.
- HealthKit allows to insert data with the unit of measurement of your choice, and automatically translates units when queried, whereas Google Fit uses fixed units of measurement.
- HealthKit automatically counts steps and distance when you carry your phone with you and if your phone has the CoreMotion chip. Google Fit does it independently on the HW chip and also detects the kind of activity (sedentary, running, walking, cycling, in vehicle).
- HealthKit can only compute distance for running/walking activities, while Google Fit can also do so for bicycle events.
Conclusion:
In this post, we are introduced to the fitness packages available in iPhone and Android devices. These fitness packages are a complete feature package in itself. But when you want those fitness data for your own Ionic 4 app, or want to write fitness data to the default device fitness package, you can do so with several different Ionic Native plugins available.
Ionic Health Plugin is the most extensive among these plugins, which allows read and write operations to both iOS HealthKit and Google Fit. It has a variety of query data sets and can perform a wide variety of functions for your app.
References
- https://developer.apple.com/documentation/healthkit#//apple_ref/doc/uid/TP40014707
- https://www.forbes.com/sites/leebelltech/2019/01/02/best-health-and-fitness-apps-2019/#45a72f9dca53
- https://www.wareable.com/apple/how-to-use-apple-health-iphone-fitness-app-960
- https://developers.google.com/fit/
- https://alternativeto.net/software/google-fit/
- https://www.androidcentral.com/google-fit-integration-and-why-you-want-it
- https://www.wareable.com/android-wear/android-wear-google-fit-watch-face-widget-lands-along-with-extra-data-1143
Top comments (0)