【问题标题】:Firebase React Native -- how to grab and transmit Device ID/Token?Firebase React Native——如何获取和传输设备 ID/令牌?
【发布时间】:2018-08-21 00:28:17
【问题描述】:

第一次使用 Firebase 和 RN 用户,试图弄清楚如何传输应用用户的设备 ID/令牌。

我现在正在使用类似这样的基本工具将信息传输到我的 firebase 数据库(使用 firebase.database().ref())。

  updateDB = (timestamp_key, item_name, item_url) => {
    firebase.database().ref(timestamp_key).set({
      item_name: item_name,
      item_url: item_url
    })
  }

关于如何获取设备令牌并传输它,我一直无法找到一个简单直接的答案(所以我知道谁的动作是谁的稍后)。

是否有(我认为应该是)一种相对简单的方法来做到这一点?谢谢!

附:除了初始化连接的配置之外,我还在脚本中调用它——也许它在附近的某个地方我需要获取设备令牌?

// Initialize Firebase
const firebaseConfig = {
  apiKey: "blah",
  authDomain: "blah",
  databaseURL: "blah",
  storageBucket: "blah",
  messagingSenderId: "blah"
};

firebase.initializeApp(firebaseConfig);

【问题讨论】:

标签: reactjs firebase react-native


【解决方案1】:

要在 React Native 中使用 firebase,您必须使用原生环境。

步骤如下:

1.退出您的应用

npm run eject

yarn run eject

2。安装 React Native Firebase (RNFirebase)

npm install --save react-native-firebase

yarn add react-native-firebase

3.按照原生设置

您需要为 firebase 应用设置原生应用配置。请按照以下步骤操作:

我不会把步骤放在这里,因为在那里迈了一大步。

4.为数据库安装依赖项

您必须为原生设置依赖项才能使用数据库库。在最后一步中,您只需设置 firebase 核心。请按照以下步骤操作:

再一次,我不是把步骤放在这里的原因长篇大论。

5.用法

获取选项的示例用法:

// get app id
firebase.app().options.appId

firebase.database().ref(path).set(val);


firebase.auth().signInAndRetrieveDataWithEmailAndPassword(email, password).then((response) => {
  console.log('signin with email', response);

  firebase.auth().currentUser.getToken().then((responseToken)=>{
    console.log('authorize', responseToken);
    this.setState({ authorize: responseToken });
  })
}).catch(function (err) {
  console.log('Unable to get sign in.', err);
});

if (Platform.OS === 'ios'){
  firebase.messaging().requestPermissions().then(() => {
    console.log('Notification permission granted.');
  }).catch((err) => {
    console.log('Unable to get permission to notify.', err);
  });
}

6.测试你的代码

通过react-native run-androidreact-native run-ios 启动您的应用取决于您的目标。

【讨论】:

  • 我认为这不能回答我正在寻找的问题(除非我误解了)。看起来您正在使用 Firebase 进行身份验证,而我只想将 deviceID(或一些等效的唯一 ID 密钥)传输到 firebase 数据库(因为我已经发送/记录 item_nameitem_url)。
【解决方案2】:

所以我也将 Expo 与 React Native 一起使用。但是,我使用的是 Google 的 Cloud Firestore,而不是实时数据库。

我不确定我是否完全理解您的问题,但这就是我的做法:

const firebase = require('firebase');
import { Constants } from 'expo';

// Required for side-effects
require('firebase/firestore');
import { firebaseConfig } from './../keys';

class Fire {
  constructor() {
    this.init();
    this.observeAuth();
  }

  init = () => firebase.initializeApp(firebaseConfig);

  observeAuth = () => firebase.auth().onAuthStateChanged(this.onAuthStateChanged);

  onAuthStateChanged = user => {
    if (!user) {
      try {
        firebase.auth().signInAnonymously();
      } catch ({ message }) {
        console.warn(message);
      }
    } else {
      this.saveUser();
    }
  };

  saveUserInfo = () => {
    const { uid } = this;
    if (!uid) {
      return;
    }
    // You can add any information here
    const info = {
      deviceId: Constants.deviceId,
    };
    const ref = this.db.collection('users').doc(uid);
    const setWithMerge = ref.set({ uid, ...info }, { merge: true });
  };

  get db() {
    return firebase.firestore();
  }
  get uid() {
    return (firebase.auth().currentUser || {}).uid;
  }
}

Fire.shared = new Fire();
export default Fire;

我从 Evan Bacon 的示例中获得了大部分代码 - https://github.com/EvanBacon/Expo-Pillar-Valley

【讨论】:

  • 我最终做的是遵循这个示例并执行var DeviceID = Constants.deviceId;,然后将 DeviceID 作为密钥传输.. 它适用于 Expo,但希望有一个更通用的答案。
猜你喜欢
  • 2020-12-20
  • 2021-02-18
  • 1970-01-01
  • 2020-02-03
  • 2017-08-21
  • 2021-09-07
  • 2012-12-15
  • 2012-10-02
相关资源
最近更新 更多