React Native Firebase 6 云消息传递和推送通知

React Native Firebase 6 cloud messaging and Push notifications

我正在使用 react native 和 firebase 6 来发送推送通知。 我使用的是新版本的官方文档: https://invertase.io/oss/react-native-firebase/v6

我为 android 和 ios 添加了本机代码来处理发送和接收通知

在我的 AndroidManifest.xml 中:

<!-- [START firebase_service] -->
        <service
            android:name=".java.MyFirebaseMessagingService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- [END firebase_service] -->

我没有创建 MyFirebaseMessagingService 。

我AppDelegate.m我添加了一些功能:

// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [FIRMessaging messaging].APNSToken = deviceToken;
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
  NSLog(@"APNs device token retrieved: %@", deviceToken);
}

// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
  NSLog(@"Unable to register for remote notifications: %@", error);
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNCPushNotificationIOS didReceiveLocalNotification:notification];
}

在我的 Component.js 中,我得到这样的令牌:

// Firebase
import firebase from '@react-native-firebase/app'
import messaging from '@react-native-firebase/messaging'

  // ----- COMPONENT DID MOUNT ---- //
  async componentDidMount () {
    // ====================================================== //
    // ====================================================== //
    // ====================================================== //
    const granted = messaging().requestPermission()

    if (granted) {
      console.log('User granted messaging permissions!')
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
      firebase
        .messaging()
        .getToken()
        .then(fcmToken => {
          if (fcmToken) {
            // user has a device token
            console.log('-------- FCM TOKEN -------')
            console.log(fcmToken)
            console.log(JSON.stringify(fcmToken))
            this._setItem(fcmToken)
          } else {
            // user doesn't have a device token yet
            console.log('error')
          }
        })
      // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
    } else {
      console.log('User declined messaging permissions :(')
    }
    // ====================================================== //
    // ====================================================== //
    // ====================================================== //
  }
  // ----- FIN COMPONENT DID MOUNT ---- //

我发送 POST 请求到 https://fcm.googleapis.com/fcm/send :

{
 "to" : "token",
 "notification" : {
 "body" : "un nouveau partage",
 "title" : "un partage de contact reçu",
 "priority" : "high",
 "vibration":true,
 "sound": "Enabled",
 "badge":1,
 "requireInteraction": true,
 "click_action": "fcm.ACTION.HELLO"
 },
 "data" : {
 "body" : "nouvelle opportunité",
 "title" : "un nouveau partage",
 "content_available" : true,
 "priority" : "high"
 } 
}

我收到了 android 和 ios 的通知,但我无法处理点击操作:

我想在用户点击通知时重定向到特定路径。

我没有将 Firebase 用于通知,但正如您所说的通知有效,那么在我看来实际的问题是您想在您的应用程序打开时处理它。

下面是您完成工作必须遵循的步骤。

  1. 在事件 onNotificationOpened 中获取通知中的数据。查看 this link 以检查您是否收到通知数据。
  2. 接下来,你要在通知的基础上进行特定的路由。我所做的是,发送屏幕类型和与该屏幕相关的 ID 以导航到那里,例如:
{
    "entity": "Place",
    "id": "123"
}

因此,当我收到通知时,我将数据发送到开关盒工厂,该工厂根据该数据中的信息导航到屏幕。诸如此类。

function navigateToScreen(entity:string, id:string){

   let screenName = "";
   let params = {}

   switch(entity){
      case "Place": 
          screenName = "placeScreen";
          params = {id};
          break;
      default: return;
   }

   // Navigation Service = https://reactnavigation.org/docs/navigating-without-navigation-prop/
   NavigationService.navigate(screenName, params);

}
  1. 现在,如果您想 运行 根据通知执行特定功能,您可以根据收到的信息执行此操作。就像在这个例子中,我必须发出一个 API 请求来通过 id 获取那个地方的数据。

const id = props.match.params['id'];

useEffect(() => {
    getThePlaceDetails(id);
}, [id]);