首页 文章

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

提问于
浏览
1

我正在使用react-native-firebase和消息来通过 Cloud 功能向我的应用程序发送通知,使用admin.messaging() . send(message),非常类似于此处:https://medium.com/the-modern-development-stack/react-native-push-notifications-with-firebase-cloud-functions-74b832d45386 .

我在应用程序处于后台时收到通知 . 现在我正在通知正文中发送一个文本,例如“新地点已添加到 Map 中” . 我希望能够添加某种深层链接,这样当我在通知上滑动View时(例如在iOS上),它会将我带到应用程序内的特定屏幕 . 如何将通知中的数据传递给应用程序?

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

3 回答

  • 1

    我认为您不需要使用深层链接或动态链接,只需正确使用Firebase / Notifications . 如果我是你,我会在你父容器的 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

  • 0

    我认为你对“firebase通知的工作方式”很好......因此,这里只是对Logic如何深入链接到你的应用程序的描述 .

    如果您发送通知,请添加数据字段 . 假设你的应用程序有一个Tab-Navigator和“新闻”,“服务”和“评论”部分 . 在推送通知 - 数据字段中(让我们将其命名为“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

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

    在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
            });
          }
    

相关问题