переходите к определенному экрану по щелчку на уведомлении firebase, используя response-native-router-flux - PullRequest
0 голосов
/ 30 апреля 2020

Я использую response-native-router-flux для навигации в response-native (0.59) в приложении. js file.И также пишу код для получения уведомлений firebase с использованием response-native-firebase в том же файле ( Приложение. js).

Мой код выглядит следующим образом: Приложение. js

   import React, { Component } from "react";
   import {
         Alert,
         DeviceEventEmitter,
         Platform,
         BackHandler,
         StyleSheet,
         View,
         Text
        } from "react-native";
      import NetInfo from "@react-native-community/netinfo";
      import firebase from "react-native-firebase";
      import {
        ActionConst,
        Actions,
        Router,
        Scene,
       Drawer
      } from "react-native-router-flux";
     import { setJSExceptionHandler } from "react-native-exception-handler";
     import CommonStyles from "./App/CommonStyle/CommonStyle";
     import { COLORS, _setItem, _getItem, appKeyConsts } from "./App/Constants";
     import DeskScreen from "./App/Auth/Components/AuthCodeComponent/DeskScreen";
     import HomeScreen from "./App/Auth/Components/UnderConstrComponent/HomeScreen";


         const Fabric = require("react-native-fabric");
         const { Crashlytics } = Fabric;
         const CleverTap = require("clevertap-react-native");
         const styles = StyleSheet.create({
          defaultFontFamily: {
           fontFamily: "lucida grande"
           }
        });



  APP_KEYS = appKeyConsts;

const scenes = Actions.create(
 <Scene
key="root"
transitionConfig={() => ({
  screenInterpolator: sceneProps => {
    const { layout, position, scene } = sceneProps;
    const { index } = scene;
    const width = layout.initWidth;

    return {
      opacity: position.interpolate({
        inputRange: [index - 1, index, index + 1],
        outputRange: [0, 1, 0]
      }),
      transform: [
        {
          translateX: position.interpolate({
            inputRange: [index - 1, index, index + 1],
            outputRange: [width, 0, 0]
          })
        }
      ]
    };
  }
})}
headerTintColor="#c30823"
backButtonTextStyle={{ color: "#000", fontSize: 13 }}
 >
  <Scene
  key="DeskScreen"
  component={DeskScreen}
  title="DeskScreen"
  hideNavBar={true}

 />

  <Scene
  key="HomeScreen"
  component={HomeScreen}
  title="HomeScreen"
  hideNavBar={true}
  // initial
/>
</Scene>
    );

   let self;
      // JS Exception handler
   const errorHandler = (e, isFatal) => {
      if (isFatal) {
  Crashlytics.setString("Error", JSON.stringify(e));
   if (Platform.OS === "android") {
  Crashlytics.logException(JSON.stringify(e));
   } else {
  Crashlytics.recordError(JSON.stringify(e));
  }
   Alert.alert(
  "Unexpected error occurred",
  `
    Error: ${isFatal ? "Fatal:" : ""} ${e.name} ${e.message}
    We have reported this to our team ! Please close the app and start again!
    `,
  [
    {
      text: "Close",
      onPress: () => {
        BackHandler.exitApp();
      }
       }
     ]
    );
   } else {
console.log(e); // So that we can see it in the ADB logs in case of Android if needed
  }
 };

    setJSExceptionHandler(errorHandler);

  class App extends Component {
    constructor(props) {
      super(props);

    // alert("code push.........")

     self = this;
      self.state = { notification: "" };
     // Forces a native crash for testing
     // Crashlytics.crash();
    }

    checkTextCutOff = () => {
    const oldRender = Text.render;
     Text.render = function(...args) {
     const origin = oldRender.call(this, ...args);
        return React.cloneElement(origin, {
      style: [styles.defaultFontFamily, origin.props.style]
    });
   };
     };

    async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
  if (enabled) {
  this.checkToken();
   } else {
  this.requestPermission();
   }
   }

    async checkToken() {
         const fcmToken = await _getItem("fcmToken");
     console.log("fcmToken", fcmToken);
       !fcmToken && self.getToken();
     }

     async getToken() {
           let fcmToken = await firebase.messaging().getToken();
    if (fcmToken) {
       // user has a device token
        console.log("token", fcmToken);
         _setItem("fcmToken", fcmToken);
        }
  }

   async requestPermission() {
   try {
   await firebase.messaging().requestPermission();
  // User has authorised
   this.checkToken();
   } catch (error) {
    // User has rejected permissions
   console.log("permission rejected");
     }
   }



     handleConnectivityChange = isConnected => {
       checkIsInternetError = isConnected;
       };

     componentDidMount() {
  NetInfo.addEventListener(
     "connectionChange",
  this.handleFirstConnectivityChange
   );
   NetInfo.isConnected.addEventListener(
  "connectionChange",
  this.handleConnectivityChange
   );


  Platform.OS !== "ios" && this.checkTextCutOff();

   this.checkPermission();
   this.createNotificationListeners();
  // Update the token whenever a new token is generated.
  this.onTokenRefreshListener = firebase
  .messaging()
  .onTokenRefresh(fcmToken => {
    _setItem("fcmToken", fcmToken);
  });


   firebase.analytics().setAnalyticsCollectionEnabled(true);
 }

  handleFirstConnectivityChange = connectionInfo => {
   NetInfo.removeEventListener(
    "connectionChange",
  this.handleFirstConnectivityChange
  );
 };

 componentWillUnmount = () => {
this.onTokenRefreshListener();
this.notificationDisplayedListener();
this.notificationListener();
 this.notificationOpenedListener();
  NetInfo.isConnected.removeEventListener(
  "connectionChange",
  this.handleConnectivityChange
);

//********************** Android back press start *****************//
    DeviceEventEmitter.removeAllListeners("hardwareBackPress");



  };


 createNotificationListeners = async () => {
/*
 * If your app is closed, you can check if it was opened by a notification being clicked / tapped / 
 opened as follows:
 * */
  const notificationOpen = await firebase
   .notifications()
  .getInitialNotification();
   if (notificationOpen) {
  const action = notificationOpen.action;
  const notification = notificationOpen.notification;


  console.log(
    "Notification opened from quit mode",
    notification._data.notificationId,
    notification
  );
  _setItem(APP_KEYS.KPUSH_NOTI, notification._data.notificationId);
  _setItem(APP_KEYS.KPUSH_TENANT_ID, notification._data.tenantId);
   }

   this.notificationDisplayedListener = firebase
  .notifications()
  .onNotificationDisplayed(notification => {
    console.log("display notification:", notification);

    // Process your notification as required
    // ANDROID: Remote notifications do not contain the channel ID. You will have to specify this 
     manually if you'd like to re-display the notification.
  });

/*
 * Triggered when app is in foreground
 * */
   const channel = new firebase.notifications.Android.Channel(
  "test-channel",
  "Test Channel",
  // firebase.notifications.Android.Importance.Max
  firebase.notifications.Android.Importance.High
   ).setDescription("My apps test channel");
   // Create the channel
   firebase.notifications().android.createChannel(channel);

   this.notificationListener = firebase
  .notifications()
  .onNotification(notification => {
    console.log("on notification received in foreground ", notification);
    if (Platform.OS === "android") {
      notification.android
        .setChannelId("test-channel") //for android 8.0 and above
        .android.setSmallIcon("ic_launcher");
      firebase.notifications().displayNotification(notification);
    } else if (Platform.OS === "ios") {
      const localNotification = new firebase.notifications.Notification()
        .setNotificationId(notification.notificationId)
        .setTitle(notification.title)
        .setSubtitle(notification.subtitle)
        .setBody(notification.body)
        .setData(notification.data)
        .ios.setBadge(notification.ios.badge);

      firebase
        .notifications()
        .displayNotification(localNotification)
        .catch(err => console.error(err));
    }
  });

/*
 * If your app is in background, you can listen for when a notification is clicked / tapped / opened 
 as follows:
 * */
this.notificationOpenedListener = firebase
  .notifications()
  .onNotificationOpened(notificationOpen => {
    console.log(
      "on notification opened from background",
      notificationOpen,
      notificationOpen.notification._data.notificationId
    );
    // this.onPressNotification(notificationOpen.notification._data);
    // Get information about the notification that was opened
    const notification = notificationOpen.notification;
    _setItem(APP_KEYS.KPUSH_NOTI, notification._data.notificationId);
    _setItem(APP_KEYS.KPUSH_TENANT_ID, notification._data.tenantId);
    firebase
      .notifications()
      .removeDeliveredNotification(notification.notificationId);
  });
    this.messageListener = firebase.messaging().onMessage(message => {
  //process data message
  console.log("message", JSON.stringify(message));
    });
 };


  render() {
   return (

    <Router scenes={scenes}  />


   );
  }
   }

 export default App;

Теперь, когда я получаю уведомление (в фоновом режиме), при нажатии на него мне нужно для перехода к определенному экрану (домашний экран). Но я не могу перейти к определенному экрану. Пожалуйста, помогите в этом

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...