【问题标题】:Deep links in react-native-firebase notificationsreact-native-firebase 通知中的深层链接
【发布时间】:2018-09-03 12:53:04
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    【解决方案2】:

    我认为您对“firebase 通知的工作方式”很好...原因,这里只是对如何深层链接到您的应用程序的逻辑的描述。

    如果您发送通知,请添加数据字段。假设您的应用有一个 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();
            }
        ....
    

    我希望这能给你一个想法,如何根据你的需要来实现它。

    【讨论】:

    • 这是在一个类中调用 all 的最佳做法,但我认为这里使用的方法适用于较旧的 react-native-firebase。
    • 对不起,我还必须配置通知模块才能访问firebase.notifications() 方法。
    【解决方案3】:

    我认为您不需要使用深层链接或动态链接,只需正确使用 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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2020-09-21
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多