Coder Social home page Coder Social logo

lucaspbordignon / rn-apple-healthkit Goto Github PK

View Code? Open in Web Editor NEW
517.0 517.0 298.0 2.81 MB

A React Native package for interacting with Apple HealthKit

Home Page: https://www.npmjs.com/package/react-native-health

License: MIT License

Objective-C 97.90% JavaScript 1.55% Ruby 0.55%
healthkit ios react react-native

rn-apple-healthkit's People

Contributors

adamivancza avatar adbl avatar alexovits avatar allenan avatar benjaminpaap avatar dependabot[bot] avatar dmatora avatar ejohnf avatar furyou81 avatar gregwilson avatar hellocore avatar iradkot avatar iradkot-herolo avatar irajeshegde avatar jacquerie avatar lucaspbordignon avatar martinrp avatar mateuszprasal avatar mcrowder65 avatar ohneeszett avatar opsb avatar shaharyarmaroof avatar skleest avatar svbutko avatar terrillo avatar thkus avatar toml0006 avatar yogiyadavmca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rn-apple-healthkit's Issues

Can't write Blood Pressure (Systolic or Diastolic)

In the documentation it states that you can write both systolic and diastolic blood pressure data. I read through the source code and can't find anything that seems to support this. Am I missing something?

Get realtime step data

Perhaps I miss understand what is possible from the technology, but I want to get real-time step data for my users.

As an example, in part of the app, I want the user to go for a walk and get 500 steps. Can I not track these steps in realtime?

I tried getDailyStepCountSamples and getStepCount, but these are aggregations for a large time period. Is there any way to monitor a 5 to 10min interval and get the number of steps as they occur?


Update: Is this what I want? initStepCountObserver

Add CocoaPods support

Currently this library won't work for anyone who has an app that has been detached from Expo (See #17), and possible anyone that uses CRNA. It'd be great if CocoaPods could be added. 😊

AppleHealthKit.saveMindfulSession() Not working

//MindfulSession
let MindFullSessionOptions = {
startDate: (new Date(2019,1,1)).toISOString(),
endDate: (new Date()).toISOString(),
};

AppleHealthKit.saveMindfulSession(MindFullSessionOptions, (err, res) => {
if (err) {
return
}
console.log('Mindful session saved')
});

I am working on this. For me success console won't display. I don't know whether any settings in the HealthKit needs to change. Please can anybody Suggest me on this.

Trouble accessing Healthkit data from React Native on PC

Hey all! I'm new to JavaScript/RN development, but I wanted to try my hand at making a small health app using data from Apple HealthKit.

I started a new project using create-react-native-app, installed rn-apple-healthkit, and linked it per README.md's instructions. However, when I import rn-apple-healthkit and run the sample code in my component, I get a TypeError. Again, I'm still pretty new to RN, so it might be that I just don't understand how the module is meant to interact with RN components. Any tips?

Here's what I'm running:

import React, { Component } from 'react';
import { View } from 'react-native';
import AppleHealthKit from 'rn-apple-healthkit';

export default class Health extends Component{
  state = { available:false };

  render(){
    let options = { permissions: { 
      read: ['Height', 'Weight', 'StepCount', 'DateOfBirth', 'BodyMassIndex'], 
      write: ['Weight', 'StepCount', 'BodyMassIndex'] } }; 

    AppleHealthKit.initHealthKit(options, (err,results) => {
      if (err){
        console.log('Error initializing Healthkit:', err)
        return;
      }
      else {
        AppleHealthKit.isAvailable((err,available) => {
          if (err) {
            console.log('Error initializing Healthkit:', err);
            return;
          }
          else {
            this.setState({ available:available })
          }
        })
      }
    })
    return(
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        {(this.state.available ? 'Yes!': 'No!')}
      </View>
    )
  }
}

Thanks in advance!

Difference between tracked steps vs user inputted?

Is there anyway to tell the difference between user inputted step data vs phone sensor data / watch data?

I currently have a sort of work around but then I am unable to tell the difference between watch step data and user inputted steps.

I use a react-native-pedometer and get the difference between health kit steps and the pedometer steps. The pedometer only returns step data recorded by the phone's sensor.

Thanks.

Test via Jest fails

Hi, import causes syntax error in testing via Jest. Do you have any idea to solve?

How to reproduce

  1. Initialize
$ react-native init <ProjectName>
$ cd <ProjectName>
  1. Confirm test pass
$ yarn test
yarn run v1.5.1
$ jest
 PASS  __tests__/App.js
  βœ“ renders correctly (105ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.506s
Ran all test suites.
✨  Done in 1.05s.
  1. Install rn-apple-healthkit
$ yarn add rn-apple-healthkit
  1. Edit App.js to import rn-apple-healthkit
diff --git a/App.js b/App.js
index dd1d45a..74f4f28 100644
--- a/App.js
+++ b/App.js
@@ -11,6 +11,7 @@ import {
   Text,
   View
 } from 'react-native';
+import AppleHealthKit from 'rn-apple-healthkit';
  1. Run test again and it fails
$ yarn test
yarn run v1.5.1
$ jest
 FAIL  __tests__/App.js
  ● Test suite failed to run

    /Users/takafumi/rn-apple-healthkit/appleHealthKit/node_modules/rn-apple-healthkit/index.js:5
    import { Permissions } from './Constants/Permissions'
    ^^^^^^

    SyntaxError: Unexpected token import

    > 1 | /**
      2 |  * Sample React Native App
      3 |  * https://github.com/facebook/react-native
      4 |  * @flow

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/script_transformer.js:316:17)
      at Object.<anonymous> (App.js:1:791)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.726s, estimated 6s
Ran all test suites.
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c jest
Directory: /Users/takafumi/rn-apple-healthkit/appleHealthKit
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/Users/takafumi/rn-apple-healthkit/appleHealthKit/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Environment

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.13.3
BuildVersion:   17D102
$ node --version
v9.8.0
$ yarn --version
1.5.1
$ react-native --version
react-native-cli: 2.0.1
react-native: 0.54.2

saveDistaceCycling

Hi there,
iΒ΄m new with this topic..

is it possible to add a "saveDistaceCycling"-methods to the RCTAppleHealthKit+Methods_Fitness.m (*.h) script?
what do I have to consider?

thanks
Linus

Cannot read body fat percentage..

Unable to read body fat percentage even though there is a method in doc ==> AppleHealthKit.getLatestBodyFatPercentage.

Am getting below error

{"message":"error getting latest body fat percentageError Domain=com.apple.healthkit Code=5 \"Authorization not determined\" UserInfo={NSLocalizedDescription=Authorization not determined}"}

Not able to call any function

Hi Terillo,

I am new to React Native, I have npm installed and link the package.

I put this code in render
let options = { permissions: { read: ['Height', 'Weight', 'StepCount', 'DateOfBirth', 'BodyMassIndex'], write: ['Weight', 'StepCount', 'BodyMassIndex'] } } AppleHealthKit.isAvailable((err: Object, available: boolean) => { if (err) { console.log('error initializing Healthkit: ', err) return } // Healthkit is available })

But this showed up

screen shot 2017-11-15 at 17 28 14

Please let me know if there is anything I should pay attention to.

how use rn-apple-healthkit

hello
i am use rn-apple-healthkit,system Prompt :

_rnAppleHealthkit2.default.getBiologicalSex is not a function. (In '_rnAppleHealthkit2.default.getBiologicalSex', '_rnAppleHealthkit2.default.getBiologicalSex' is undefined)

componentDidMount
    index.ios.js:43:40
measureLifeCyclePerf
    ReactNativeStack-dev.js:1610:15
<unknown>
    ReactNativeStack-dev.js:1657:33
notifyAll
    ReactNativeStack-dev.js:2121:107
close
    ReactNativeStack-dev.js:2138:8
closeAll
    ReactNativeStack-dev.js:1412:101
perform
    ReactNativeStack-dev.js:1388:52
batchedMountComponentIntoNode
    ReactNativeStack-dev.js:2004:24
perform
    ReactNativeStack-dev.js:1382:99
renderComponent
    ReactNativeStack-dev.js:2032:45
renderApplication
    renderApplication.js:34:4
runApplication
    AppRegistry.js:191:26
__callFunction
    MessageQueue.js:306:47
<unknown>
    MessageQueue.js:108:26
__guard
    MessageQueue.js:269:6
callFunctionReturnFlushedQueue
    MessageQueue.js:107:17

How should I get the data?

I am index.ios.js inside ,Next, how do I get the data?

import AppleHealthKit from 'rn-apple-healthkit';
let options = {
    permissions: {
        read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
        write: ["Weight", "StepCount", "BodyMassIndex"]
    }
};

Save Food

I have a few questions about 'save food' feature:

  1. Why it is not presented in read me while it is available in the source code?

  2. I found that saveFood is not very stable. Sometimes it saves food, but most of the time it doesn't. Also, the callback function is not getting called when it doesn't save, which makes it is very hard to suggest what is going wrong. Any thoughts about it?

New HealthKit data in iOS 11.3

11.3 (in beta as of this writing) adds many new healthkit constants because it uses FHIR to connect directly with electronic health systems, i.e. patient medical records. Is anyone working on adding these new data types to this library? For example LDL Cholesterol, or medications.

AppleHealthkit.getBloodPressureSamples only working once

Hello, thanks for the great package!

We are using it in our app to import Apple Health data and aggregate it with blood pressure data users can input in our app as well.

When the permission is granted for us to read Apple Health data, the data I am requesting is successfully communicated to our app, where we can work with it.

But if I add another value in Apple Health after this and call AppleHealthkit.getBloodPressureSamples again, no new data is found and no error is caught.

Is this expected behaviour?

I hope this is enough to understand the problem, otherwise I can post some code as well.

User added values?

Any way to map in items like Body Temperature added by a Thermo thermometer?

Active Calories and other additional data types for GetSamples()

Is there a way to get more data types from the GetSamples method? Specifically I am looking to get Active Calories, which currently is not available. The main motivation for wanting this is being able to access the isTracked property.

Side note: The data types for the getSamples method are not very clear. For example, the Running type is for "Distance Walking/Running" but Running suggests it is just for running. Similarly, Walking is steps, which come from walking as well as running.

HealthKit cannot initialize

after installing the library and calling AppleHealthKit.initHealthKit
I get the following error:
screen shot 2018-05-23 at 6 33 43 pm

When I inspect the AppleHealthKit imported object, there is just "constants" and "permissions" properties, no methods.

Unhandled JS Exception: _this._fetchStepCountData is not a function

I follow the setting and code with rn-apple-healthkit's document

However I got a strange mistake !!

Anyone have the answer?

`import React, { Component } from 'react';
import {
ScrollView,
Navigator,
View,
NativeAppEventEmitter,
} from 'react-native';
import axios from 'axios';
import AppleHealthKit from 'rn-apple-healthkit';

import AlbumDetail from './AlbumDetail';

const d = new Date();

const PERMS = AppleHealthKit.Constants.Permissions;

const HKOPTIONS = {
permissions: {
read: [
PERMS.StepCount,
PERMS.Height,
PERMS.Weight,
PERMS.DateOfBirth,
PERMS.BodyMassIndex,
],
write: [
PERMS.StepCount,
PERMS.Weight,
PERMS.BodyMassIndex,
],
},
date: d.toISOString()
};

AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
if (err) {
console.log('HealthkitInitError: ', err);
return;
}
console.log('HealthkitInitSucess');

AppleHealthKit.initStepCountObserver({}, () => {});

this.sub = NativeAppEventEmitter.addListener(
'change:steps',
(event) => {
// mistake is here!!!
this._fetchStepCountData();
console.log(event);
}
);
});

// StepCounter Example
AppleHealthKit.getStepCount(HKOPTIONS, (error, results) => {
if (error) {
console.log('getStepCountError: ', error);
return;
}
console.log(results);
});

class albumList extends Component {
state = { albums: [] };

componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }))
.then(response => console.log(response));
}

componentDidMount() {
console.log(this.state.albums);
}

// when the component where the listener was added unmounts, call the 'remove' method of the subscription object.
componentWillUnmount() {
this.sub.remove();
};

renderAlbums() {
return this.state.albums.map(album =>

);
}
render() {
return (

{this.renderAlbums()}

);
}
}

export default albumList;`

Step counts only showing last 15 days

I'm using the code from the example from the original repo readme: https://www.npmjs.com/package/react-native-apple-healthkit#getdailystepcountsamples

    const options = {
      startDate: (new Date(2016,5,1)).toISOString(), 
      endDate:   (new Date()).toISOString()
    }
    AppleHealthKit.getDailyStepCountSamples(options: Object, (err: Object, steps: Object) => {
      if (err) {
        console.log('error', err);
        return;
      }
      console.log(steps)
    });

This start date is obviously very long ago, but no matter what dates I set in the getDailyStepCountSamples I can only get the last 15 days of steps.

I am running on my device. Is this a bug or is it only possible to get the last 15 days? If I use other dates that start and end outside of the last 15 days I just get an empty array, no error.

React/RCTBridgeDelegate.h file not found

EDIT - I'm really confused. The file is in the directory /Users/adamhanna/Desktop/goLang/src/personal/rise/rise/node_modules/react-native/React/Base, when I add that exact directory to my headers search path, it still errors. WTH?!

I installed the project automatically with yarn and react-native link rn-apple-healthkit but I'm still getting this error. See the error and my header search paths in the image, below. I'm at my wits end, any help would be appreciated. Thx

screen shot 2017-12-08 at 12 00 33 am

Build fails on 'React/RCTBridgeModule.h' file not found

Is this library compatible with the latest versions of React Native? I can't get it to work, as there seems to be some issues with Header imports not being found. I've searched for hours with potential fixes such as changing the Header Search paths, but no luck.

'React/RCTBridgeModule.h' file not found

Shot

React Native Version
0.51.0

I've tried running Clean in Xcode after removing the rn-apple-healthkit and unlinking, then reinstalling again, still the issue persists.

Has anyone else been able to get it to build on newer versions of React Native?

Updating repo & looking for collaborators

Hey Everyone,

Looking to add collaborators. I'm going to start reviewing open pull requests and get the ball rolling again. πŸ‘

Comment below if your interested in becoming a collaborator.

_this2._handleHealthKitError is not a function

When I tried to run the code, I am getting "_this2._handleHealthKitError is not a function" error. If I comment "this._handleHealthKitError () ", getting the result as { value: null, age: null }.

[RFC] Gathering/observing data in the background and foreground

This feature will add background observers for an arbitrary number of types of data. Below are my notes and ideas for how to implement this. Your comments and ideas are welcome.

I propose the following:

  1. The app can be initialized with an additional option: observe
    E.g:
let options = {
  permissions: {
    read: ["Height", "Weight", "StepCount", "DateOfBirth", "BodyMassIndex"],
    write: ["Weight", "StepCount", "BodyMassIndex"],
  },
  observers: [
    { type: "StepCount" },
    { type: "Weight" }
  ]
};
AppleHealthKit.initHealthKit(options);
  1. Observers (HKObserverQuery) run in the background, saving data to AsyncStorage, perhaps to the RNAppleHealthkit key. To retrieve it later you could run:
const healthKitData = await AsyncStorage.getItem('RNAppleHealthkit');
const steps = healthKitData.StepCount;
// `steps` might contains something like:
// [
//    { date: '1 1 2019', value: 10000}
// ]
  1. To make use of this most effectively, use react-native-background-fetch
BackgroundFetch.configure({
  minimumFetchInterval: 15, // <-- minutes (15 is minimum allowed)
}, () => {

  // Retrieve data
  const healthKitData = await AsyncStorage.getItem('RNAppleHealthkit');

  // Stop if there isn't any
  if (!healthKitData)  {
    BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NO_DATA);
  }

  // Get steps
  const steps = healthKitData.StepCount;

  // Upload them
  await fetch('http://placetouploadsteps.com/steps', { method: 'POST', body: JSON.stringify({ steps });

  // No need to waste storage
  AsyncStorage.removeItem('RNAppleHealthkit');

  // Finish
  BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);

}, (error) => {
  console.log("[js] RNBackgroundFetch failed to start");
});
  1. Event triggers still work, if your app is in the foreground (but with a simpler API)
    Per https://github.com/terrillo/rn-apple-healthkit/blob/master/docs/initStepCountObserver().md
import { EventEmitter } from 'rn-apple-healthkit';
EventEmitter.addListener(
  'change:StepCount',
  (evt) => {
    const steps = evt.data;
  }
);

Is it possible to detect if a user has activeEnergy activated?

I am building an app based on activeEnergy, but as I understand it, it's only available if you are using an apple watch (I am guessing fitbit as well). Is it possible to detect this? I want to default back to stepcount for users without an apple watch.

Listener 'observer' take a while to fire ?

I'm building application that want to show user step in realtime but listener take too long to invoke.
Is it possible to show healthkit user step in realtime ?

this is my code

async componentDidmount() {
    AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
        if (err) {
            console.log('error initializing Healthkit: ', err);
            return;
        }
        AppleHealthKit.setObserver({ type: 'Walking' });
        NativeAppEventEmitter.addListener('observer', () => console.log('fetch new data'));
    });
}

'React/RCTBridgeModule.h' file not found

I followed the manual install directions exactly and when I build the project I am receiving this error.

the line is: #import <React/RCTBridgeModule.h>
line 12 of RCTAppleHealthKit.h

"react": "15.3.2",
"react-native": "0.34.1",
"rn-apple-healthkit": "^0.6.3",

Filter manual entered data

We are developing an App which give you "Coins" when you reached an achievement. You can manually enter step in Health Kit. Is it possible to filter out this manual entered data.

Health Records API

Hi.
I just want to ask if you have a plan to make this to support new Health Records API?
Thanks

getSleepSamples() and getBloodPressureSamples() Not working

getSleepSamples() and getBloodPressureSamples() never return any data. I've triple checked that my app has permission to read data from HealthKit and that data is present however both functions never return any data. I think it's those functions particularly because calling getStepCount() with the same setup/options works fine

CODE:

//Pedometer permissions stuff
const HKPERMISSIONS = AppleHealthKit.Constants.Permissions;

//Options for all Apple Healthkit features
let OPTIONS = {
permissions: {
read: [HKPERMISSIONS.StepCount, HKPERMISSIONS.SleepAnalysis, HKPERMISSIONS.BloodPressureDiastolic, HKPERMISSIONS.BloodPressureSystolic],
write: [HKPERMISSIONS.StepCount]
}
};

let BLOODOPTIONS = {
unit: 'mmhg', // optional; default 'mmhg'
startDate: (new Date(2018,5,20)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
ascending: false, // optional; default false
limit:10, // optional; default no limit
}

let SLEEPOPTIONS = {
startDate: (new Date(2018,5,20)).toISOString(), // required
endDate: (new Date()).toISOString(), // optional; default now
//limit:10, // optional; default no limit
};

...

AppleHealthKit.initHealthKit(OPTIONS, (err, res) => {
if(this._handleHealthKitError(err, 'initHealthKit')) {
return;
}
// healthkit initialized...

          //Blood Pressure Example
          
          AppleHealthKit.getBloodPressureSamples(BLOODOPTIONS, (err: Object, results: Array<Object>) => {
            if (err) {
              return;
            }
            console.warn("BLOOD: " + results);
          });
          
          
      //Sleep Analysis
        
      AppleHealthKit.getSleepSamples(SLEEPOPTIONS, (err: Object, res:Array<Object>) => {
        if (err) {
          console.warn("ERROR: " + err)
        return;
        }
        console.warn("SLEEP: " + res)
      });

...

}

Steps in decimal

It works well on iPhone 5 , iPhone 5s etc.
When I check this on iPhone X. The steps are in decimals. I receive the object in the format:

0: endDate:"2018-04-07T00:00:00.000+0530" startDate:"2018-04-06T00:00:00.000+0530" value:5213.434565464534535 __proto__:Object length:1 __proto__:Array(0)

Typo in initHealthKit() wiki

Please replace AppleHealthkit.initHealthKit with AppleHealthKit.initHealthKit (uppercase K in AppleHealthKit) in the last code snippet in the initHealthKit() wiki.
EDIT: This typo is repeated in many other Wiki pages as well.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.