如何在 React Native 中获取设备令牌

How to get the device token in react native

我使用的是 react-native 0.49.3 版本,我的问题是如何在 IOS 和 Android 的 react native 中获取设备令牌 我试过这个 link但它对我不起作用,现在我在 IOS 中尝试过。如何解决 能否告诉我如何配置?

我尝试了不同的解决方案,我决定使用 React Native Firebase

Here 您会找到有关通知的所有信息。

此外,您还可以使用 Firebase 附带的其他库,例如 Analytics 和崩溃报告

设置库后,您可以执行以下操作:

// 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() {
    ...
  }
}

然后您可以使用令牌和您需要的所有信息调用服务器。