README.md 31.7 KB
Newer Older
Terrillo Walls's avatar
Terrillo Walls committed
1
# React Native Apple HealthKit
2
A React Native bridge module for interacting with [Apple HealthKit] data.
Greg Wilson's avatar
Greg Wilson committed
3

Greg Wilson's avatar
Greg Wilson committed
4
![Alt text](https://devimages.apple.com.edgekey.net/assets/elements/icons/healthkit/healthkit-64x64.png "Apple HealthKit")
Greg Wilson's avatar
Greg Wilson committed
5

Greg Wilson's avatar
Greg Wilson committed
6
## Table of Contents
Greg Wilson's avatar
Greg Wilson committed
7
  * [Getting Started](#getting-started)
Greg Wilson's avatar
Greg Wilson committed
8
    * [Installation](#installation)
Greg Wilson's avatar
Greg Wilson committed
9 10 11 12
    * [Usage](#usage)
  * [Documentation](#documentation)
    * [Permissions](#permissions)
    * [Methods](#methods)
Greg Wilson's avatar
Greg Wilson committed
13
      * [isAvailable](#isavailable)
Greg Wilson's avatar
Greg Wilson committed
14
      * [initHealthKit](#inithealthkit)
Greg Wilson's avatar
Greg Wilson committed
15 16
      * [getBiologicalSex](#getbiologicalsex)
      * [getDateOfBirth](#getdateofbirth)
Greg Wilson's avatar
Greg Wilson committed
17
      * [getStepCount](#getstepcount)
Greg Wilson's avatar
Greg Wilson committed
18
      * [getDailyStepCountSamples](#getdailystepcountsamples)
19
      * [initStepCountObserver](#initstepcountobserver)
Greg Wilson's avatar
Greg Wilson committed
20
      * [saveSteps](#savesteps)
Greg Wilson's avatar
Greg Wilson committed
21 22 23
      * [getDistanceWalkingRunning](#getdistancewalkingrunning)
      * [getDistanceCycling](#getdistancecycling)
      * [getFlightsClimbed](#getflightsclimbed)
Greg Wilson's avatar
Greg Wilson committed
24
      * [getLatestWeight](#getlatestweight)
Greg Wilson's avatar
Greg Wilson committed
25
      * [getWeightSamples](#getweightsamples)
Greg Wilson's avatar
Greg Wilson committed
26 27
      * [saveWeight](#saveweight)
      * [getLatestHeight](#getlatestheight)
Greg Wilson's avatar
Greg Wilson committed
28
      * [getHeightSamples](#getheightsamples)
Greg Wilson's avatar
Greg Wilson committed
29 30 31 32 33
      * [saveHeight](#saveheight)
      * [getLatestBmi](#getlatestbmi)
      * [saveBmi](#savebmi)
      * [getLatestBodyFatPercentage](#getlatestbodyfatpercentage)
      * [getLatestLeanBodyMass](#getlatestleanbodymass)
Daniele Volpi's avatar
Daniele Volpi committed
34 35 36 37 38
      * [getHeartRateSamples](#getheartratesamples)
      * [getBodyTemperatureSamples](#getbodytemperaturesamples)
      * [getBloodPressureSamples](#getbloodpressuresamples)
      * [getRespiratoryRateSamples](#getrespiratoryratesamples)
      * [getBloodGlucoseSamples](#getbloodglucosesamples)
39
      * [getSleepSamples](#getsleepsamples)
Greg Wilson's avatar
Greg Wilson committed
40
  * [Examples](#examples)
41

Terrillo Walls's avatar
Terrillo Walls committed
42 43
## References
- Apple HealthKit Documentation [https://developer.apple.com/healthkit/](https://developer.apple.com/healthkit/)
Greg Wilson's avatar
Greg Wilson committed
44

Greg Wilson's avatar
Greg Wilson committed
45 46
## Getting started

Greg Wilson's avatar
Greg Wilson committed
47 48
###  Installation

Terrillo Walls's avatar
Terrillo Walls committed
49
Install the [rn-apple-healthkit] package from npm:
Greg Wilson's avatar
Greg Wilson committed
50

Terrillo Walls's avatar
Terrillo Walls committed
51
`npm install rn-apple-healthkit --save`
Greg Wilson's avatar
Greg Wilson committed
52

Greg Wilson's avatar
Greg Wilson committed
53
##### Xcode
54

Greg Wilson's avatar
Greg Wilson committed
55
1. In XCode, in the project navigator, right click `Libraries``Add Files to [your project's name]`
Terrillo Walls's avatar
Terrillo Walls committed
56
2. Go to `node_modules``rn-apple-healthkit` and add `RCTAppleHealthKit.xcodeproj`
Greg Wilson's avatar
Greg Wilson committed
57 58
3. In XCode, in the project navigator, select your project. Add `libRCTAppleHealthKit.a` to your project's `Build Phases``Link Binary With Libraries`
4. Click `RCTAppleHealthKit.xcodeproj` in the project navigator and go the `Build Settings` tab. Make sure 'All' is toggled on (instead of 'Basic'). In the `Search Paths` section, look for `Header Search Paths` and make sure it contains both `$(SRCROOT)/../../react-native/React` and `$(SRCROOT)/../../../React` - mark both as `recursive`.
Greg Wilson's avatar
Greg Wilson committed
59 60
5. Enable HealthKit in your application's `Capabilities`
![Alt text](/examples/images/Capabilities_HealthKit.png "Xcode Capabilities Section")
Greg Wilson's avatar
Greg Wilson committed
61

Greg Wilson's avatar
Greg Wilson committed
62
6. Compile and run
Greg Wilson's avatar
Greg Wilson committed
63

Greg Wilson's avatar
Greg Wilson committed
64
### Usage
Greg Wilson's avatar
Greg Wilson committed
65

Terrillo Walls's avatar
Terrillo Walls committed
66
Just `require` the `rn-apple-healthkit` module and you're ready to go!
Terrillo Walls's avatar
Terrillo Walls committed
67

Greg Wilson's avatar
Greg Wilson committed
68
```javascript
Terrillo Walls's avatar
Terrillo Walls committed
69
var AppleHealthKit = require('rn-apple-healthkit');
Greg Wilson's avatar
Greg Wilson committed
70

Greg Wilson's avatar
Greg Wilson committed
71 72
...

Greg Wilson's avatar
Greg Wilson committed
73
let options = {
Greg Wilson's avatar
Greg Wilson committed
74
    permissions: {
Greg Wilson's avatar
Greg Wilson committed
75 76
        read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
        write: ["Weight", "StepCount", "BodyMassIndex"]
Greg Wilson's avatar
Greg Wilson committed
77 78 79
    }
};

Greg Wilson's avatar
Greg Wilson committed
80
AppleHealthKit.initHealthKit(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
81 82 83 84
    if(err) {
        console.log("error initializing healthkit: ", err);
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
85
    // healthkit initialized...
Greg Wilson's avatar
Greg Wilson committed
86 87 88 89 90
});


```

Greg Wilson's avatar
Greg Wilson committed
91 92 93
When the module has been successfully initialized you can read and write HealthKit data

```javascript
Terrillo Walls's avatar
Terrillo Walls committed
94
var AppleHealthKit = require('rn-apple-healthkit');
Greg Wilson's avatar
Greg Wilson committed
95 96 97 98
var _ = require('lodash');

...

Greg Wilson's avatar
Greg Wilson committed
99
AppleHealthKit.getLatestWeight(null, (err: Object, weight: Object) => {
Greg Wilson's avatar
Greg Wilson committed
100 101 102 103
    if(err){
        console.log("error getting current weight: ", err);
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
104
    // use weight.value ...
Greg Wilson's avatar
Greg Wilson committed
105 106 107 108
});

...

Greg Wilson's avatar
Greg Wilson committed
109 110
let options = {value: 200};
AppleHealthKit.saveWeight(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
111 112 113 114 115 116 117 118 119
    if(err){
        console.log("error saving weight to healthkit: ", err);
        return;
    }
    // weight successfully saved
});


```
Greg Wilson's avatar
Greg Wilson committed
120 121


Greg Wilson's avatar
Greg Wilson committed
122 123 124

## Documentation

Greg Wilson's avatar
Greg Wilson committed
125 126
Permissions
-----------
Greg Wilson's avatar
Greg Wilson committed
127

128
The available HealthKit permissions to use with `initHealthKit`
Greg Wilson's avatar
Greg Wilson committed
129

Greg Wilson's avatar
Greg Wilson committed
130 131
| Permission             | HealthKit Identifier Type                                                                                                                                      | Read | Write |
|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|------|-------|
Terrillo Walls's avatar
Terrillo Walls committed
132 133 134
| ActiveEnergyBurned     | [HKQuantityTypeIdentifierActiveEnergyBurned](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifieractiveenergyburned?language=objc)         | ✓    | ✓     |
| AppleExerciseTime      | [HKQuantityTypeIdentifierAppleExerciseTime](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierappleexercisetime?language=objc)           | ✓    |       |
| BasalEnergyBurned      | [HKQuantityTypeIdentifierBasalEnergyBurned](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierbasalenergyburned?language=objc)           | ✓    | ✓     |
Greg Wilson's avatar
Greg Wilson committed
135
| BiologicalSex          | [HKCharacteristicTypeIdentifierBiologicalSex](https://developer.apple.com/reference/healthkit/hkcharacteristictypeidentifierbiologicalsex?language=objc)       | ✓    |       |
Terrillo Walls's avatar
Terrillo Walls committed
136
| BloodGlucose           | [HKQuantityTypeIdentifierBloodGlucose](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierbloodglucose?language=objc)                     | ✓    |       |
Greg Wilson's avatar
Greg Wilson committed
137
| BodyMassIndex          | [HKQuantityTypeIdentifierBodyMassIndex](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierbodymassindex?language=objc)                   | ✓    | ✓     |
Terrillo Walls's avatar
Terrillo Walls committed
138 139 140
| BodyTemperature        | [HKQuantityTypeIdentifierBodyTemperature](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierbodytemperature?language=objc)               | ✓    |       |
| DateOfBirth            | [HKCharacteristicTypeIdentifierDateOfBirth](https://developer.apple.com/reference/healthkit/hkcharacteristictypeidentifierdateofbirth?language=objc)           | ✓    |       |
| DietaryEnergy          | [HKQuantityTypeIdentifierDietaryEnergyConsumed](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierdietaryenergyconsumed?language=objc)   | ✓    | ✓     |
Greg Wilson's avatar
Greg Wilson committed
141
| DistanceCycling        | [HKQuantityTypeIdentifierDistanceCycling](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierdistancecycling?language=objc)               | ✓    | ✓     |
Terrillo Walls's avatar
Terrillo Walls committed
142
| DistanceWalkingRunning | [HKQuantityTypeIdentifierDistanceWalkingRunning](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierdistancewalkingrunning?language=objc) | ✓    | ✓     |
Greg Wilson's avatar
Greg Wilson committed
143
| FlightsClimbed         | [HKQuantityTypeIdentifierFlightsClimbed](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierflightsclimbed?language=objc)                 | ✓    | ✓     |
Daniele Volpi's avatar
Daniele Volpi committed
144
| HeartRate              | [HKQuantityTypeIdentifierHeartRate](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierheartrate?language=objc)                           | ✓    |       |
Terrillo Walls's avatar
Terrillo Walls committed
145 146 147
| Height                 | [HKQuantityTypeIdentifierHeight](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierheight?language=objc)                                 | ✓    | ✓     |
| LeanBodyMass           | [HKQuantityTypeIdentifierLeanBodyMass](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierleanbodymass?language=objc)                     | ✓    | ✓     |
| NikeFuel               | [HKQuantityTypeIdentifierNikeFuel](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifiernikefuel?language=objc)                             | ✓    |       |
Daniele Volpi's avatar
Daniele Volpi committed
148
| RespiratoryRate        | [HKQuantityTypeIdentifierRespiratoryRate](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierrespiratoryrate?language=objc)               | ✓    |       |
Terrillo Walls's avatar
Terrillo Walls committed
149 150 151 152
| SleepAnalysis          | [HKCategoryTypeIdentifierSleepAnalysis](https://developer.apple.com/reference/healthkit/hkcategorytypeidentifiersleepanalysis?language=objc)                   | ✓    |       |
| StepCount              | [HKQuantityTypeIdentifierStepCount](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierstepcount?language=objc)                           | ✓    | ✓     |
| Steps                  | [HKQuantityTypeIdentifierSteps](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifiersteps?language=objc)                                   | ✓    | ✓     |
| Weight                 | [HKQuantityTypeIdentifierBodyMass](https://developer.apple.com/reference/healthkit/hkquantitytypeidentifierbodymass?language=objc)                             | ✓    | ✓     |
Greg Wilson's avatar
Greg Wilson committed
153

Terrillo Walls's avatar
Terrillo Walls committed
154
These permissions are exported as constants of the `rn-apple-healthkit` module.
Greg Wilson's avatar
Greg Wilson committed
155 156

```javascript
Terrillo Walls's avatar
Terrillo Walls committed
157
import AppleHealthKit from 'rn-apple-healthkit';
Greg Wilson's avatar
Greg Wilson committed
158 159 160 161 162 163

...

// get the available permissions from AppleHealthKit.Constants object
const PERMS = AppleHealthKit.Constants.Permissions;

Greg Wilson's avatar
Greg Wilson committed
164
// setup healthkit read/write permissions using PERMS
Greg Wilson's avatar
Greg Wilson committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
const healthKitOptions = {
    permissions: {
        read:  [
            PERMS.StepCount,
            PERMS.Height,
        ],
        write: [
            PERMS.StepCount
        ],
    }
};

...
```

Greg Wilson's avatar
Greg Wilson committed
180

Greg Wilson's avatar
Greg Wilson committed
181 182
Options
-------
Greg Wilson's avatar
Greg Wilson committed
183 184


Greg Wilson's avatar
Greg Wilson committed
185 186
Methods
-------
Greg Wilson's avatar
Greg Wilson committed
187

188
#### **`isAvailable`**
Greg Wilson's avatar
Greg Wilson committed
189
Check if HealthKit is available on the device.
Greg Wilson's avatar
Greg Wilson committed
190
```javascript
Greg Wilson's avatar
Greg Wilson committed
191
AppleHealthKit.isAvailable((err: Object, available: boolean) => {
Greg Wilson's avatar
Greg Wilson committed
192 193 194 195 196
    if(available){
        // ...
    }
});
```
Greg Wilson's avatar
Greg Wilson committed
197
___
Greg Wilson's avatar
Greg Wilson committed
198

199 200
#### **`initHealthKit`**
Initialize HealthKit. This will show the HealthKit permissions prompt for any read/write permissions set in the required `options` object.
Greg Wilson's avatar
Greg Wilson committed
201

202
Due to Apple's privacy model if an app user has previously denied a specific permission then they can not be prompted again for that same permission. The app user would have to go into the Apple Health app and grant the permission to your react-native app under *sources* tab.
Greg Wilson's avatar
Greg Wilson committed
203

Greg Wilson's avatar
Greg Wilson committed
204
For any data that is read from HealthKit the status/error is the same for both. This privacy restriction results in having no knowledge of whether the permission was denied (make sure it's added to the permissions options object), or the data for the specific request was nil (ex. no steps recorded today).
Greg Wilson's avatar
Greg Wilson committed
205

Greg Wilson's avatar
Greg Wilson committed
206
For any data written to HealthKit an authorization error can be caught. If an authorization error occurs you can prompt the user to set the specific permission or add the permission to the options object if not present.
Greg Wilson's avatar
Greg Wilson committed
207

Greg Wilson's avatar
Greg Wilson committed
208
If new read/write permissions are added to the options object then the app user will see the HealthKit permissions prompt with the new permissions to allow.
Greg Wilson's avatar
Greg Wilson committed
209 210

`initHealthKit` requires an options object with HealthKit permission settings
Greg Wilson's avatar
Greg Wilson committed
211
```javascript
Greg Wilson's avatar
Greg Wilson committed
212
let options = {
Greg Wilson's avatar
Greg Wilson committed
213
    permissions: {
Greg Wilson's avatar
Greg Wilson committed
214 215
        read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
        write: ["Weight", "StepCount", "BodyMassIndex"]
Greg Wilson's avatar
Greg Wilson committed
216 217
    }
};
Greg Wilson's avatar
Greg Wilson committed
218
```
Greg Wilson's avatar
Greg Wilson committed
219

Greg Wilson's avatar
Greg Wilson committed
220
```javascript
Greg Wilson's avatar
Greg Wilson committed
221
AppleHealthKit.initHealthKit(options: Object, (err: string, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
222 223 224 225 226 227 228 229 230
    if(err) {
        console.log("error initializing healthkit: ", err);
        return;
    }
    // healthkit is initialized...
    // now safe to read and write healthkit data...
});
```

Greg Wilson's avatar
Greg Wilson committed
231 232
___

Greg Wilson's avatar
Greg Wilson committed
233
#### **`getBiologicalSex`**
Greg Wilson's avatar
Greg Wilson committed
234
Get the biological sex (gender). If the `BiologicalSex` read permission is missing or the user has denied it then the value will be `unknown`. The possible values are:
Greg Wilson's avatar
Greg Wilson committed
235

Greg Wilson's avatar
Greg Wilson committed
236 237 238 239 240 241 242 243
| Value   | HKBiologicalSex       |
|---------|-----------------------|
| unknown | HKBiologicalSexNotSet |
| male    | HKBiologicalSexMale   |
| female  | HKBiologicalSexFemale |
| other   | HKBiologicalSexOther  |

```javascript
244
AppleHealthKit.getBiologicalSex(null, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
245 246 247
    if(this._handleHealthKitError(err, 'getBiologicalSex')){
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
248
	// res.value will be one of the values from the above table (Value column)
249
    // use res.value ...
Greg Wilson's avatar
Greg Wilson committed
250 251 252 253 254
});
```

___

Greg Wilson's avatar
Greg Wilson committed
255
#### **`getDateOfBirth`**
256
Get the date of birth.
Greg Wilson's avatar
Greg Wilson committed
257

Greg Wilson's avatar
Greg Wilson committed
258
On success, the callback function will be provided with a `res` object containing dob `value: string` (ISO timestamp), and `age: number` (age in years):
Greg Wilson's avatar
Greg Wilson committed
259
```javascript
260 261 262
{
	value: '1986-09-01T00:00:00.000-0400',
	age: 29
263 264 265 266 267
}
```

```javascript
AppleHealthKit.getDateOfBirth(null, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
268 269 270
    if(this._handleHealthKitError(err, 'getDateOfBirth')){
        return;
    }
271 272
    // use res.value ... (ex: '1986-09-01T12:20:30-04:00')
	// use res.age ... (ex: 29)
Greg Wilson's avatar
Greg Wilson committed
273 274 275 276 277
});
```

___

Greg Wilson's avatar
Greg Wilson committed
278
#### **`getStepCount`**
279
Get the aggregated total steps for a specific day (starting and ending at midnight).
Greg Wilson's avatar
Greg Wilson committed
280

281
An optional options object may be provided containing `date` field representing the selected day. If `date` is not set or an options object is not provided then the current day will be used.
Greg Wilson's avatar
Greg Wilson committed
282 283 284 285 286 287 288
```javascript
let d = new Date(2016,5,27);
let options = {
    date: d.toISOString()
};
```

Greg Wilson's avatar
Greg Wilson committed
289
```javascript
Greg Wilson's avatar
Greg Wilson committed
290 291 292 293 294 295 296 297 298 299
AppleHealthKit.getStepCount(options: Object, (err: Object, steps: Object) => {
    if(this._handleHealthKitError(err, 'getStepCount')){
        return;
    }
    // steps.value is the step count for day 'd'
});
```

___

Greg Wilson's avatar
Greg Wilson committed
300
#### **`getDailyStepCountSamples`**
301
Get the total steps per day over a specified date range.
Greg Wilson's avatar
Greg Wilson committed
302

Greg Wilson's avatar
Greg Wilson committed
303
`getDailyStepCountSamples` accepts an options object containing required *`startDate: ISO8601Timestamp`* and optional *`endDate: ISO8601Timestamp`*. If `endDate` is not provided it will default to the current time
Greg Wilson's avatar
Greg Wilson committed
304 305 306 307 308 309
```javascript
let options = {
    startDate: (new Date(2016,5,1)).toISOString()  // required
    endDate:   (new Date()).toISOString()          // optional; default now
};
```
Greg Wilson's avatar
Greg Wilson committed
310
The function will be called with an array of elements. Each element is an object containing `value`, `startDate`, and `endDate` fields:
Greg Wilson's avatar
Greg Wilson committed
311
```javascript
312
[
Greg Wilson's avatar
Greg Wilson committed
313 314 315 316 317 318 319 320
  { value: 8, startDate: '2016-07-09T00:00:00.000-0400', endDate: '2016-07-10T00:00:00.000-0400' },
  { value: 1923, startDate: '2016-07-08T00:00:00.000-0400', endDate: '2016-07-09T00:00:00.000-0400' },
  { value: 1802, startDate: '2016-07-07T00:00:00.000-0400', endDate: '2016-07-08T00:00:00.000-0400' },
  ...
]
```


Greg Wilson's avatar
Greg Wilson committed
321
```javascript
Greg Wilson's avatar
Greg Wilson committed
322
 AppleHealthKit.getDailyStepCountSamples(options: Object, (err: Object, res: Array<Object>) => {
Greg Wilson's avatar
Greg Wilson committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    if(this._handleHealthKitError(err, 'getDailyStepCountSamples')){
        return;
    }
    // 'res' is array of {value: number, startDate: string, endDate: string} objects
    // sorted ascending from startDate through endDate
    for(let i=0; i<res.length; ++i){
        let elem = res[i];
        let stepCount = elem.value;
        let day = elem.startDate;
		// ...
    }
});
```

___

339 340 341 342
#### **`initStepCountObserver`**
Setup an HKObserverQuery for step count (HKQuantityTypeIdentifierStepCount) that will
trigger an event listenable on react-native `NativeAppEventEmitter` when the
HealthKit step count has changed.
Greg Wilson's avatar
Greg Wilson committed
343

344 345 346 347 348 349 350 351
The `initStepCountObserver` method must be called before adding a listener to
NativeAppEventEmitter. After the step count observer has been initialized you can
listen to the NativeAppEventEmitter `change:steps` event and re-fetch relevent
step count data in the event handler.

The `initStepCountObserver` method should be called after HealthKit has been
successfully initialized (AppleHealthKit.initHealthKit has been called without
error).
352 353

```javascript
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
// import NativeAppEventEmitter from react-native
import {
  Navigator,
  View,
  ...
  NativeAppEventEmitter,
} from 'react-native';

...

// initialize the step count observer and add an event
// listener for 'change:steps' event after HealthKit has
// been successfully initialized.
AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
  if(this._handleHKError(err, 'initHealthKit')){
    return;
  }

  // initialize the step count observer
  AppleHealthKit.initStepCountObserver({}, () => {});

  // add event listener for 'change:steps' and handle the
  // event in the event handler function.
  //
  // when adding a listener, a 'subscription' object is
  // returned that must be used to remove the listener
  // when the component unmounts. The subscription object
  // must be accessible to any function/method/instance
  // that will be unsubscribing from the event.
  this.sub = NativeAppEventEmitter.addListener(
    'change:steps',
    (evt) => {
      // a 'change:steps' event has been received. step
      // count data should be re-fetched from HealthKit.
      this._fetchStepCountData();
389
    }
390
  );
Greg Wilson's avatar
Greg Wilson committed
391 392 393 394 395 396

  // other tasks to perform after HealthKit has been
  // initialized (fetch relevant HealthKit data).
  this._fetchStepCountData();
  this._fetchOtherRelevantHealthKitData();
  // ...
397
});
398 399 400 401 402

...

// when the component where the listener was added unmounts
// (or whenever the listener should be removed), call the
Greg Wilson's avatar
Greg Wilson committed
403
// 'remove' method of the subscription object.
404 405 406
componentWillUnmount() {
  this.sub.remove();
}
407 408 409 410
```

___

Greg Wilson's avatar
Greg Wilson committed
411
#### **`saveSteps`**
Greg Wilson's avatar
Greg Wilson committed
412
Save a step count sample.
Greg Wilson's avatar
Greg Wilson committed
413

Greg Wilson's avatar
Greg Wilson committed
414
A step count sample represents the number of steps during a specific period of time. A sample should be a precise as possible, with startDate and endDate representing the range of time the steps were taken in.
Greg Wilson's avatar
Greg Wilson committed
415 416 417

`saveSteps` accepts an options object containing required *`value: number`*, *`startDate: ISO8601Timestamp`*, and *`endDate: ISO8601Timestamp`*.
```javascript
418
// startDate and endDate are 30 minutes apart.
Greg Wilson's avatar
Greg Wilson committed
419
// this means the step count value occured within those 30 minutes.
Greg Wilson's avatar
Greg Wilson committed
420 421 422 423 424 425 426 427 428
let options = {
	value: 100,
	startDate: (new Date(2016,6,2,6,0,0)).toISOString(),
	endDate: (new Date(2016,6,2,6,30,0)).toISOString()
};
```

```javascript
AppleHealthKit.saveSteps(options, (err, res) => {
429
  if(this._handleHKError(err, 'saveSteps')){
Greg Wilson's avatar
Greg Wilson committed
430 431 432 433 434 435 436 437
		return;
	}
	// step count sample successfully saved
});
```

___

Greg Wilson's avatar
Greg Wilson committed
438
#### **`getDistanceWalkingRunning`**
439
Get the total distance walking/running on a specific day.
Greg Wilson's avatar
Greg Wilson committed
440

Greg Wilson's avatar
Greg Wilson committed
441
`getDistanceWalkingRunning` accepts an options object containing optional *`date: ISO8601Timestamp`* and *`unit: string`*. If `date` is not provided it will default to the current time. `unit` defaults to `meter`.
Greg Wilson's avatar
Greg Wilson committed
442 443 444 445 446 447 448 449
```javascript
let options = {
	unit: 'mile',									// optional; default 'meter'
    date: (new Date(2016,5,1)).toISOString(),  		// optional; default now
};
```

```javascript
Greg Wilson's avatar
Greg Wilson committed
450
AppleHealthKit.getDistanceWalkingRunning(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
451 452 453
    if(this._handleHKError(err, 'getDistanceWalkingRunning')){
    	return;
    }
Greg Wilson's avatar
Greg Wilson committed
454
	// use res.value ...
Greg Wilson's avatar
Greg Wilson committed
455 456 457 458 459 460
});
```

___

#### **`getDistanceCycling`**
461
Get the total distance cycling on a specific day.
Greg Wilson's avatar
Greg Wilson committed
462

Greg Wilson's avatar
Greg Wilson committed
463
`getDistanceCycling` accepts an options object containing optional *`date: ISO8601Timestamp`* and *`unit: string`*. If `date` is not provided it will default to the current time. `unit` defaults to `meter`
Greg Wilson's avatar
Greg Wilson committed
464 465 466 467 468 469 470 471
```javascript
let options = {
	unit: 'meter',									// optional; default 'meter'
    date: (new Date(2016,5,1)).toISOString(),  		// optional; default now
};
```

```javascript
Greg Wilson's avatar
Greg Wilson committed
472
AppleHealthKit.getDistanceCycling(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
473 474 475
    if(this._handleHKError(err, 'getDistanceCycling')){
    	return;
    }
Greg Wilson's avatar
Greg Wilson committed
476
	// use res.value ...
Greg Wilson's avatar
Greg Wilson committed
477 478 479 480 481 482
});
```

___

#### **`getFlightsClimbed`**
483
get the total flights climbed (1 flight is ~10ft of elevation) on a specific day.
Greg Wilson's avatar
Greg Wilson committed
484 485 486 487 488 489 490 491 492

`getFlightsClimbed` accepts an options object containing optional *`date: ISO8601Timestamp`*. if `date` is not provided it will default to the current time.
```javascript
let options = {
    date: (new Date(2016,5,1)).toISOString(),  		// optional; default now
};
```

```javascript
Greg Wilson's avatar
Greg Wilson committed
493
AppleHealthKit.getFlightsClimbed(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
494 495 496
    if(this._handleHKError(err, 'getFlightsClimbed')){
    	return;
    }
Greg Wilson's avatar
Greg Wilson committed
497
	// use res.value ...
Greg Wilson's avatar
Greg Wilson committed
498 499 500 501 502
});
```

___

503
#### **`getLatestWeight`**
Greg Wilson's avatar
Greg Wilson committed
504 505
Get the most recent weight sample.

Greg Wilson's avatar
Greg Wilson committed
506
On success, the callback function will be provided with a `weight` object containing the weight `value`, and the `startDate` and `endDate` of the weight sample. *Note: startDate and endDate will be the same as weight samples are saved at a specific point in time.*
Greg Wilson's avatar
Greg Wilson committed
507 508 509
```javascript
{
	value: 200,
510
	startDate: '2016-07-08T12:00:00.000-0400',
Greg Wilson's avatar
Greg Wilson committed
511 512 513 514
	endDate: '2016-07-08T12:00:00.000-0400'
}
```

Greg Wilson's avatar
Greg Wilson committed
515
```javascript
Greg Wilson's avatar
Greg Wilson committed
516
AppleHealthKit.getLatestWeight(null, (err: string, weight: Object) => {
Greg Wilson's avatar
Greg Wilson committed
517
    if(err){
518
        console.log("error getting latest weight: ", err);
Greg Wilson's avatar
Greg Wilson committed
519 520
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
521
    // use weight.value, weight.startDate, etc ...
Greg Wilson's avatar
Greg Wilson committed
522 523 524
});
```

Greg Wilson's avatar
Greg Wilson committed
525 526
___

Greg Wilson's avatar
Greg Wilson committed
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
#### **`getWeightSamples`**
query for weight samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'pound',										// optional; default 'pound'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```

```javascript
AppleHealthKit.getWeightSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getWeightSamples')){
		return;
	}
	// use samples ...
});
```

___

Greg Wilson's avatar
Greg Wilson committed
550 551
#### **`saveWeight`**
save a numeric weight value to HealthKit
Greg Wilson's avatar
Greg Wilson committed
552

Greg Wilson's avatar
Greg Wilson committed
553
`saveWeight` accepts an options object containing a numeric weight value:
Greg Wilson's avatar
Greg Wilson committed
554
```javascript
Greg Wilson's avatar
Greg Wilson committed
555
let options = {value: 200}
Greg Wilson's avatar
Greg Wilson committed
556 557
```
```javascript
Greg Wilson's avatar
Greg Wilson committed
558
AppleHealthKit.saveWeight(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
559 560 561 562 563 564 565
    if(err){
        console.log("error saving weight to healthkit: ", err);
        return;
    }
    // weight successfully saved
});
```
Greg Wilson's avatar
Greg Wilson committed
566

567 568 569
___

#### **`getLatestHeight`**
Greg Wilson's avatar
Greg Wilson committed
570 571
Get the most recent height value.

Greg Wilson's avatar
Greg Wilson committed
572
On success, the callback function will be provided with a `height` object containing the height `value`, and the `startDate` and `endDate` of the height sample. *Note: startDate and endDate will be the same as height samples are saved at a specific point in time.*
573
```javascript
Greg Wilson's avatar
Greg Wilson committed
574 575
{
	value: 72,
576
	startDate: '2016-07-08T12:00:00.000-0400',
Greg Wilson's avatar
Greg Wilson committed
577 578 579 580 581 582 583
	endDate: '2016-07-08T12:00:00.000-0400'
}
```


```javascript
AppleHealthKit.getLatestHeight(null, (err: string, height: Object) => {
584 585 586 587
    if(err){
        console.log("error getting latest height: ", err);
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
588
    // use height.value, height.startDate, etc ...
589 590
});
```
Greg Wilson's avatar
Greg Wilson committed
591 592 593

___

Greg Wilson's avatar
Greg Wilson committed
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
#### **`getHeightSamples`**
query for height samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'inch',										// optional; default 'inch'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```

the callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields
```javascript
// samples is array of objects
[
Greg Wilson's avatar
Greg Wilson committed
610 611
	{value: 74.02, startDate:'2016-06-29T17:55:00.000-0400', endDate:'2016-06-29T17:55:00.000-0400'},
	{value: 74, startDate:'2016-03-12T13:22:00.000-0400', endDate:'2016-03-12T13:22:00.000-0400'},
Greg Wilson's avatar
Greg Wilson committed
612 613 614
	...
]
```
Greg Wilson's avatar
Greg Wilson committed
615
*example usage*
Greg Wilson's avatar
Greg Wilson committed
616 617 618 619 620 621 622 623 624 625 626
```javascript
AppleHealthKit.getHeightSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getHeightSamples')){
		return;
	}
	// use samples ...
});
```

___

Greg Wilson's avatar
Greg Wilson committed
627 628 629 630 631 632 633 634
#### **`saveHeight`**
save a numeric height value to HealthKit

`saveHeight` accepts an options object containing a numeric height value:
```javascript
let options = {value: 200}
```
```javascript
Greg Wilson's avatar
Greg Wilson committed
635
AppleHealthKit.saveHeight(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
636 637 638 639 640 641 642
    if(this._handleHealthKitError(err, 'saveHeight')){
        return;
    }
    // height successfully saved
});
```

Greg Wilson's avatar
Greg Wilson committed
643 644 645
___

#### **`getLatestBmi`**
646
Get the most recent BMI sample.
Greg Wilson's avatar
Greg Wilson committed
647

Greg Wilson's avatar
Greg Wilson committed
648
On success, the callback function will be provided with a `bmi` object containing the BMI `value`, and the `startDate` and `endDate` of the sample. *Note: startDate and endDate will be the same as bmi samples are saved at a specific point in time.*
Greg Wilson's avatar
Greg Wilson committed
649 650 651
```javascript
{
	value: 27.2,
652
	startDate: '2016-07-08T12:00:00.000-0400',
Greg Wilson's avatar
Greg Wilson committed
653 654 655 656
	endDate: '2016-07-08T12:00:00.000-0400'
}
```

Greg Wilson's avatar
Greg Wilson committed
657 658 659 660 661 662
```javascript
AppleHealthKit.getLatestBmi(null, (err: string, bmi: Object) => {
    if(err){
        console.log("error getting latest bmi data: ", err);
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
663 664 665
    let d = bmi.startDate
    let val = bmi.value;
    // ...
Greg Wilson's avatar
Greg Wilson committed
666 667 668
});
```

669 670
___

Greg Wilson's avatar
Greg Wilson committed
671 672 673 674 675 676 677 678
#### **`saveBmi`**
save a numeric BMI value to HealthKit

`saveBmi` accepts an options object containing a numeric BMI value:
```javascript
let options = {value: 27.2}
```
```javascript
Greg Wilson's avatar
Greg Wilson committed
679
AppleHealthKit.saveBmi(options: Object, (err: Object, res: Object) => {
Greg Wilson's avatar
Greg Wilson committed
680 681 682 683 684 685 686 687 688
    if(this._handleHealthKitError(err, 'saveBmi')){
        return;
    }
    // BMI successfully saved
});
```

___

689
#### **`getLatestBodyFatPercentage`**
Greg Wilson's avatar
Greg Wilson committed
690 691
Get the most recent body fat percentage. The percentage value is a number between 0 and 100.

Greg Wilson's avatar
Greg Wilson committed
692
On success, the callback function will be provided with a `bodyFatPercentage` object containing the body fat percentage `value`, and the `startDate` and `endDate` of the sample. *Note: startDate and endDate will be the same as bodyFatPercentage samples are saved at a specific point in time.*
Greg Wilson's avatar
Greg Wilson committed
693 694 695
```javascript
{
	value: 20,
696
	startDate: '2016-07-08T12:00:00.000-0400',
Greg Wilson's avatar
Greg Wilson committed
697 698 699 700
	endDate: '2016-07-08T12:00:00.000-0400'
}
```

701
```javascript
Greg Wilson's avatar
Greg Wilson committed
702
AppleHealthKit.getLatestBodyFatPercentage(null, (err: Object, bodyFatPercentage: Object) => {
703 704 705
    if(this._handleHealthKitError(err, 'getLatestBodyFatPercentage')){
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
706
    // use bodyFatPercentage.value, bodyFatPercentage.startDate, etc ...
707 708 709
});
```

Greg Wilson's avatar
Greg Wilson committed
710 711 712
___

#### **`getLatestLeanBodyMass`**
Greg Wilson's avatar
Greg Wilson committed
713 714
Get the most recent lean body mass. The value is a number representing the weight in pounds (lbs)

Greg Wilson's avatar
Greg Wilson committed
715
On success, the callback function will be provided with a `leanBodyMass` object containing the leanBodyMass `value`, and the `startDate` and `endDate` of the sample. *Note: startDate and endDate will be the same as leanBodyMass samples are saved at a specific point in time.*
Greg Wilson's avatar
Greg Wilson committed
716 717 718
```javascript
{
	value: 176,
719
	startDate: '2016-07-08T12:00:00.000-0400',
Greg Wilson's avatar
Greg Wilson committed
720 721 722 723
	endDate: '2016-07-08T12:00:00.000-0400'
}
```

Greg Wilson's avatar
Greg Wilson committed
724
```javascript
Greg Wilson's avatar
Greg Wilson committed
725
 AppleHealthKit.getLatestLeanBodyMass(null, (err: Object, leanBodyMass: Object) => {
Greg Wilson's avatar
Greg Wilson committed
726 727 728
    if(this._handleHealthKitError(err, 'getLatestLeanBodyMass')){
        return;
    }
Greg Wilson's avatar
Greg Wilson committed
729
    // use leanBodyMass.value, leanBodyMass.startDate, etc ...
Greg Wilson's avatar
Greg Wilson committed
730 731
});
```
Greg Wilson's avatar
Greg Wilson committed
732

Daniele Volpi's avatar
Daniele Volpi committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872
___

#### **`getHeartRateSamples`**
query for heart rate samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'bpm',										// optional; default 'bpm'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```

the callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields

*example usage*
```javascript
AppleHealthKit.getHeartRateSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getHeartRateSamples')){
		return;
	}
	// use samples ...
});
```

___

#### **`getBodyTemperatureSamples`**
query for body temperature samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'celsius',									// optional; default 'celsius'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```
available units are: `'fahrenheit'`, `'celsius'`.

the callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields.

*example usage*
```javascript
AppleHealthKit.getBodyTemperatureSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getBodyTemperatureSamples')){
		return;
	}
	// use samples ...
});
```

___

#### **`getBloodPressureSamples`**
query for blood pressure samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'mmhg',								    	// optional; default 'mmhg'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```

the callback function will be called with a `samples` array containing objects with *bloodPressureSystolicValue*, *bloodPressureDiastolicValue*, *startDate*, and *endDate* fields
```javascript
// samples is array of objects
[
	{bloodPressureSystolicValue: 120, bloodPressureDiastolicValue: 81, startDate:'2016-06-29T17:55:00.000-0400', endDate:'2016-06-29T17:55:00.000-0400'},
	{bloodPressureSystolicValue: 119, bloodPressureDiastolicValue: 77, startDate:'2016-03-12T13:22:00.000-0400', endDate:'2016-03-12T13:22:00.000-0400'},
	...
]
```
*example usage*
```javascript
AppleHealthKit.getBloodPressureSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getBloodPressureSamples')){
		return;
	}
	// use samples ...
});
```

___

#### **`getRespiratoryRateSamples`**
query for respiratory rate samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'bpm',								    	// optional; default 'bpm'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```

the callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields

*example usage*
```javascript
AppleHealthKit.getRespiratoryRateSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getRespiratoryRateSamples')){
		return;
	}
	// use samples ...
});
```

___

#### **`getBloodGlucoseSamples`**
query for blood glucose samples. the options object is used to setup a query to retrieve relevant samples.
```javascript
let options = {
    unit: 'mmolPerL',							    	// optional; default 'mmolPerL'
    startDate: (new Date(2016,4,27)).toISOString(),		// required
	endDate: (new Date()).toISOString(),				// optional; default now
    ascending: false,									// optional; default false
    limit:10,											// optional; default no limit
};
```
available units are: `'mmolPerL'`, `'mgPerdL'`.

the callback function will be called with a `samples` array containing objects with *value*, *startDate*, and *endDate* fields

*example usage*
```javascript
AppleHealthKit.getBloodGlucoseSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getBloodGlucoseSamples')){
		return;
	}
	// use samples ...
});
```


873 874 875 876 877 878 879
___

#### **`getSleepSamples`**
query for sleep samples.

each sleep sample represents a period of time with a startDate and an endDate.
the sample's value will be either `INBED` or `ASLEEP`. these values should overlap,
Greg Wilson's avatar
Greg Wilson committed
880
meaning that two (or more) samples represent a single nights sleep activity. see
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
[HealthKit SleepAnalysis] reference documentation

the options object is used to setup a query to retrieve relevant samples.
the options must contain `startDate` and may also optionally include `endDate`
and `limit` options
```javascript
let options = {
    startDate: (new Date(2016,10,1)).toISOString(),		// required
	  endDate: (new Date()).toISOString(),				// optional; default now
    limit:10,											// optional; default no limit
};
```

the callback function will be called with a `samples` array containing objects
with *value*, *startDate*, and *endDate* fields

*example usage*
```javascript
AppleHealthKit.getSleepSamples(options, (err: Object, samples: Array<Object>) => {
	if(this._handleHealthKitError(err, 'getSleepSamples')){
		return;
	}
	// use samples ...
});
```

Greg Wilson's avatar
Greg Wilson committed
907
## Examples
Terrillo Walls's avatar
Terrillo Walls committed
908 909
- [Steps Demo](https://github.com/GregWilson/rn-apple-healthkit/tree/master/examples/StepsDemo)
- [Body Measurements Demo](https://github.com/GregWilson/rn-apple-healthkit/tree/master/examples/BodyMeasurements)
Greg Wilson's avatar
Greg Wilson committed
910

Terrillo Walls's avatar
Terrillo Walls committed
911
> *This package is fork from [react-native-apple-healthkit](https://github.com/GregWilson/react-native-apple-healthkit)*