Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the device token in react native

I am using react-native 0.49.3 version, My Question is how to get the device token in react native for both IOS and Android I tried with this link but it not working for me, right now I tried in IOS. how to resolve it can one tell me how to configure?

like image 578
achu Avatar asked Nov 09 '17 05:11

achu


1 Answers

I tried different solutions and I've decided to use React Native Firebase.

Here you will find everything about Notifications.

Also, you can use the others libraries that come with Firebase, like Analytics and Crash Reporting

After set up the library you can do something like:

// utils/firebase.js
import RNFirebase from 'react-native-firebase';

const configurationOptions = {
  debug: true,
  promptOnMissingPlayServices: true
}

const firebase = RNFirebase.initializeApp(configurationOptions)

export default firebase


// App.js
import React, { Component } from 'react';
import { Platform, View, AsyncStorage } from 'react-native';

// I am using Device info
import DeviceInfo from 'react-native-device-info';

import firebase  from './utils/firebase';

class App extends Component {

 componentDidMount = () => {
    var language = DeviceInfo.getDeviceLocale();

    firebase.messaging().getToken().then((token) => {
       this._onChangeToken(token, language)
    });

    firebase.messaging().onTokenRefresh((token) => {
        this._onChangeToken(token, language)
    });
  }

  _onChangeToken = (token, language) => {
    var data = {
      'device_token': token,
      'device_type': Platform.OS,
      'device_language': language
    };

    this._loadDeviceInfo(data).done();
  }

  _loadDeviceInfo = async (deviceData) => {
    // load the data in 'local storage'.
    // this value will be used by login and register components.
    var value = JSON.stringify(deviceData);
    try {
      await AsyncStorage.setItem(config.DEVICE_STORAGE_KEY, value);
    } catch (error) {
      console.log(error);
    }
  };  

  render() {
    ...
  }
}

Then you can call the server with the token and all the info that you need.

like image 139
Marcos Schroh Avatar answered Sep 24 '22 02:09

Marcos Schroh