react-native-firebase通知中的深层链接

时间:2018-09-03 12:53:04

标签: react-native react-native-navigation react-native-firebase

我正在使用带有消息传递的react-native-firebase通过admin.messaging()。send(message)将消息通过云功能发送到我的应用程序,与此处类似:https://medium.com/the-modern-development-stack/react-native-push-notifications-with-firebase-cloud-functions-74b832d45386

当应用程序在后台运行时,我会收到通知。现在,我正在通知的正文中发送文本,例如“地图上已添加新位置”。我希望能够添加某种深层链接,以便当我在通知上滑动“查看”时(例如在iOS上),它将带我到应用程序内的特定屏幕。如何将数据从通知传递到应用程序?

我在应用程序中使用react-native-navigation。我只能从应用程序(https://wix.github.io/react-native-navigation/#/deep-links?id=deep-links)中找到有关深层链接的代码。

3 个答案:

答案 0 :(得分:3)

我认为您对“ firebase通知的工作方式”没什么问题……原因,这里仅是对如何深层链接到您的应用程序的逻辑的描述。

如果发送通知,请添加一个数据字段。假设您的应用程序具有一个Tab导航器,以及“新闻”,“服务”和“审阅”部分。 在您的“推送通知-数据”字段中(将其命名为“ jumpToScreen”),您可以定义值:

  

jumpToScreen =服务

我认为您仍然实现了从Firebase接收通知的处理。 因此,创建一个/lib/MessageHandler.js类,并将您的业务逻辑放入其中。

import firebase from 'react-native-firebase';

/*
 * Get a string from Firebase-Messages and return the Screen to jump to
 */
const getJumpPoint = (pointer) => {
  switch (pointer) {
    case 'News':
      return 'NAV_NewsList'; // <= this are the names of your Screens
    case 'Service':
      return 'NAV_ServiceList';
    case 'Review':
      return 'NAV_ReviewDetail';
    default: return false;
  }
};

const MessageHandler = {
  /**
   *  initPushNotification  initialize Firebase Messaging
   *  @return fcmToken String
   */
  initPushNotification: async () => {
    try {
      const notificationPermission = await firebase.messaging().hasPermission();
      MessageHandler.setNotificationChannels();

      if (notificationPermission) {
        try {
          return await MessageHandler.getNotificationToken();
        } catch (error) {
          console.log(`Error: failed to get Notification-Token \n ${error}`);
        }
      }
    } catch (error) {
      console.log(`Error while checking Notification-Permission\n ${error}`);
    }
    return false;
  },
  clearBadges:  () => {
    firebase.notifications().setBadge(0);
  },
  getNotificationToken: () => firebase.messaging().getToken(),
  setNotificationChannels() {
    try {
      /* Notification-Channels is a must-have for Android >= 8 */
      const channel = new firebase.notifications.Android.Channel(
        'app-infos',
        'App Infos',
        firebase.notifications.Android.Importance.Max,
      ).setDescription('General Information');

      firebase.notifications().android.createChannel(channel);
    } catch (error) {
      console.log('Error while creating Push_Notification-Channel');
    }
  },
  requestPermission: () => {
    try {
      firebase.messaging().requestPermission();
      firebase.analytics().logEvent('pushNotification_permission', { decision: 'denied' });
    } catch (error) {
      // User has rejected permissions
      firebase.analytics().logEvent('pushNotification_permission', { decision: 'allowed' });
    }
  },
  foregroundNotificationListener: (navigation) => {
    // In-App Messages if App in Foreground
    firebase.notifications().onNotification((notification) => {
      MessageHandler.setNotificationChannels();
      navigation.navigate(getJumpPoint(notification.data.screen));
    });
  },
  backgroundNotificationListener: (navigation) => {
    // In-App Messages if App in Background
    firebase.notifications().onNotificationOpened((notificationOpen) => {
      const { notification } = notificationOpen;
      notification.android.setChannelId('app-infos');
      if (notification.data.screen !== undefined) {
        navigation.navigate(getJumpPoint(notification.data.screen));
      }
    });
  },
  appInitNotificationListener: () => {
    // In-App Messages if App in Background
    firebase.notifications().onNotificationOpend((notification) => {
      notification.android.setChannelId('app-infos');
      console.log('App-Init: Da kommt ne Message rein', notification);
      firebase.notifications().displayNotification(notification);
    });
  },
};

export default MessageHandler;

在index.js中,您可以像这样连接它:

import MessageHandler from './lib/MessageHandler';
export default class App extends Component {
    state = {
      loading: null,
      connection: null,
      settings: null,
    };
async componentDidMount() {
    const { navigation } = this.props;
    await MessageHandler.initPushNotification();
    this.notificationForegroundListener = MessageHandler.foregroundNotificationListener(navigation);
    this.notificationBackgroundListener = MessageHandler.backgroundNotificationListener(navigation);

    this.setState({ loading: false, data });
  }

    componentWillUnmount() {
        this.notificationForegroundListener();
        this.notificationBackgroundListener();
    }
    async componentDidMount() {
      MessageHandler.requestPermission();
      AppState.addEventListener('change', this.handleAppStateChange);
      MessageHandler.clearBadges();
    }

    componentWillUnmount() {
      AppState.removeEventListener('change', this.handleAppStateChange);
    }
    handleAppStateChange = (nextAppState) => {
        if (nextAppState.match(/inactive|background/)) {
           MessageHandler.clearBadges();
        }
    ....

我希望这能给您一个想法,以实现您的需求。

答案 1 :(得分:1)

我认为您不需要使用深层链接或动态链接,而只需正确使用Firebase /通知即可。如果您是我,请在您的父容器的componentDidMount方法中添加以下逻辑:

async componentDidMount() {

    // 1. Check notification permission
    const notificationsEnabled = await firebase.messaging().hasPermission();
    if (!notificationsEnabled) {
        try {
            await firebase.messaging().requestPermission(); // Request notification permission
            // At this point the user has authorized the notifications
        } catch (error) {
            // The user has NOT authorized the notifications
        }
    }

    // 2. Get the registration token for firebase notifications
    const fcmToken = await firebase.messaging().getToken();
    // Save the token

    // 3. Listen for notifications. To do that, react-native-firebase offer you some methods:
    firebase.messaging().onMessage(message => { /*  */ })

    firebase.notifications().onNotificationDisplayed(notification => { /* */ })

    firebase.messaging().onNotification(notification => { /*  */ })

    firebase.messaging().onNotificationOpened(notification => { 
        /* For instance, you could use it and do the NAVIGATION at this point
        this.props.navigation.navigate('SomeScreen');
        // Note that you can send whatever you want in the *notification* object, so you can add to the notification the route name of the screen you want to navigate to.
        */
    })

}

您可以在此处找到文档:https://rnfirebase.io/docs/v4.3.x/notifications/receiving-notifications

答案 2 :(得分:1)

我的解决方案是在通知消息对象的数据对象中添加所需的信息:

在functions / index.js中:

  let message = {
    notification: {
      body: `new notification `
    },
    token: pushToken,
    data: {
      type: 'NEW_TRAINING',
      title: locationTitle
    }
  };

并在应用中进行以下导航操作:

this.notificationOpenedListener =
      firebase.notifications().onNotificationOpened((notificationOpen: NotificationOpen) => {
      if (notification.data.type === 'NEW_TRAINING') {
        this.props.navigator.push({
          screen: 'newtrainingscreen',
          title: notification.data.title,
          animated: true
        });
      }