index.js 6 KB
Newer Older
1 2 3 4 5 6 7 8 9
/**
 * Created by greg on 2016-06-30.
 */

import React, { Component } from 'react';
import {
    Navigator,
    TouchableOpacity,
    ScrollView,
10
    Image,
11 12 13
    Text,
    View
} from 'react-native';
14
import AppleHealthKit from 'react-native-apple-healthkit';
15
import styles from '../../styles/styles';
16 17
import History from './history';

18
// setup the HealthKit initialization options
19 20
const WPERMS = AppleHealthKit.Constants.Permissions.WRITE;
const RPERMS = AppleHealthKit.Constants.Permissions.READ;
21 22
const HKOPTIONS = {
    permissions: {
23 24 25
        read:  [
            RPERMS.StepCount,
            RPERMS.DistanceWalkingRunning,
Greg Wilson's avatar
Greg Wilson committed
26 27
            RPERMS.FlightsClimbed,
            RPERMS.Height,
28
        ],
29 30 31
        write: [
            WPERMS.StepCount
        ],
32 33 34
    }
};

35 36 37
/**
 * React Component
 */
38 39 40 41 42 43 44 45 46 47
class Home extends Component {

    constructor(props) {
        super(props);
        this.state = {
            stepsToday: 0,
            stepHistory: [],
        };
    }

48 49 50 51 52
    /**
     * if HealthKit is available on the device then initialize it
     * with the permissions set above in HKOPTIONS. on successful
     * initialization fetch today's steps and the step history
     */
53 54 55 56 57 58 59 60 61
    componentDidMount() {
        AppleHealthKit.isAvailable((err,available) => {
            if(available){
                AppleHealthKit.initHealthKit(HKOPTIONS, (err, res) => {
                    if(this._handleHKError(err, 'initHealthKit')){
                        return;
                    }
                    this._fetchStepsToday();
                    this._fetchStepsHistory();
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

                    //setTimeout(() => {
                    //
                    //    let options = {
                    //        value: 350,
                    //        startDate: (new Date(2016,6,2,6,0,0)).toISOString(),
                    //        endDate: (new Date(2016,6,2,6,30,0)).toISOString()
                    //    };
                    //    AppleHealthKit.saveSteps(options, (err, res) => {
                    //        if(this._handleHKError(err, 'saveSteps')){
                    //            return;
                    //        }
                    //        console.log('steps saved...');
                    //    });
                    //
                    //},1000);

79 80 81 82 83
                });
            }
        });
    }

84 85 86 87 88
    /**
     * get today's step count from HealthKit. on success update
     * the component state
     * @private
     */
89 90 91 92 93 94 95 96 97
    _fetchStepsToday() {
        AppleHealthKit.getStepCountForToday(null, (err, steps) => {
            if(this._handleHKError(err, 'getStepCountForToday')){
                return;
            }
            this.setState({stepsToday: steps});
        });
    }

98 99 100 101 102
    /**
     * get the step history from options.startDate through the
     * current time. on success update the component state
     * @private
     */
103 104 105 106 107 108 109 110 111 112 113 114
    _fetchStepsHistory() {
        let options = {
            startDate: (new Date(2016,4,1)).toISOString(),
        };
        AppleHealthKit.getDailyStepSamples(options, (err, res) => {
            if(this._handleHKError(err, 'getDailyStepSamples')){
                return;
            }
            this.setState({stepHistory: res});
        });
    }

115 116 117 118 119
    /**
     * render the Navigator which will render the navigation
     * bar and the scene
     * @returns {XML}
     */
120 121 122 123 124 125 126 127 128 129 130 131
    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                navigationBar={
                    <Navigator.NavigationBar style={styles.navigationBar}
                                             routeMapper={NavigationBarRouteMapper} />
                }/>
        );
    }

132 133 134 135 136 137
    /**
     * render the scene
     * @param route
     * @param navigator
     * @returns {XML}
     */
138 139 140 141 142
    renderScene(route, navigator) {
        return (
            <View style={styles.sceneContainerWithNavbar}>

                <View style={styles.stepsContainer}>
143 144 145 146 147 148 149 150 151
                    <Image style={styles.stepsIcon}
                           source={require('../../assets/images/steps.png')}>

                    </Image>
                    <Text style={styles.stepsLabel}>
                        Today's Steps
                    </Text>
                    <Text style={styles.stepsValue}>
                        {this.state.stepsToday}
152 153 154 155
                    </Text>
                </View>

                <View style={styles.historyContainer}>
156 157 158 159 160
                    <View style={styles.titleRow}>
                        <Text>
                            History
                        </Text>
                    </View>
161 162 163 164 165 166 167
                    <History data={this.state.stepHistory} />
                </View>

            </View>
        );
    }

168 169 170 171 172 173 174 175
    /**
     * if 'err' is truthy then log the error message and
     * return true indicating an error has occurred
     * @param err
     * @param method
     * @returns {boolean}
     * @private
     */
176 177 178
    _handleHKError(err, method) : boolean {
        if(err){
            let errStr = 'HealthKit_ERROR['+method+'] : ';
179
            errStr += (err && err.message) ? err.message : err;
180 181 182 183 184 185 186 187 188 189 190 191 192
            console.log(errStr);
            return true;
        }
        return false;
    }
}


var NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, nextState) {
        return null;
    },
    RightButton(route, navigator, index, nextState) {
193 194 195 196 197 198 199 200
        return (
            <TouchableOpacity style={styles.navbarTitleTouchable}
                              onPress={() => { navigator.parentNavigator.push({name: 'Add'})}}>
                <Text style={styles.navbarPlusButton}>
                    +
                </Text>
            </TouchableOpacity>
        );
201 202 203 204 205 206 207 208 209 210 211 212 213 214
    },
    Title(route, navigator, index, nextState) {
        return (
            <TouchableOpacity style={styles.navbarTitleTouchable}>
                <Text style={styles.navbarTitle}>
                    HealthKit Steps
                </Text>
            </TouchableOpacity>
        );
    }
};

module.exports = Home;
export default Home;