Firebase React Native - 如何获取和传输设备ID/令牌?

11

我是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
    })
  }

我一直没有找到一个简单明了的答案,说明如何获取设备令牌并将其传输(以便我知道稍后是谁的操作)。

有没有一种相对简单的方法可以做到这一点?谢谢!

P.S. 除了配置文件初始化连接之外,我还在脚本中较高的位置调用它--也许在这里我需要获取设备令牌?

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

firebase.initializeApp(firebaseConfig);

https://firebase.google.com/docs/cloud-messaging/js/client#access_the_registration_token - Doug Stevenson
很遗憾,出现了错误。请参考此链接 https://dev59.com/rKLia4cB1Zd3GeqPfzy9 - SpicyClubSauce
你是如何创建你的项目的? - bennygenel
@bennygenel,你能详细说明一下你的意思吗?我正在使用Expo。 - SpicyClubSauce
如果您使用react-native init创建了项目,我建议您使用一些本地库。 - bennygenel
2个回答

2

我也在使用Expo和React Native,但是我使用的是谷歌的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 来说是有效的,但希望有一个更通用的答案。 - SpicyClubSauce

0

在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进行身份验证,而我只想将设备ID(或某个等效的唯一ID键)传输到Firebase数据库中(因为我已经发送/记录了“item_name”和“item_url”)。 - SpicyClubSauce

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接