react-native

react-native集成FCM的消息推送功能

2024-03-13  本文已影响0人  sunny635533

前提背景:
用于海外的推送消息开发,一开始是集成firebase原生库,android是没问题的,但是ios cocospod添加FireBase第三方库,一直编译报错,与Flipper库包冲突。所以放弃这个方式,改成集成RN的@react-native-firebase/app和@react-native-firebase/messaging的库。

官方文档:https://rnfirebase.io/
1、用yarn 添加这两个库:

yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging

android配置按照这个文档 https://rnfirebase.io/
ios的配置除了pod文件的修改不要按照这个文档,其他步骤需要做的。

image.png
截图上千万不能照做!
ios的pod添加的替代代码如下:
#pod文件的顶部添加
RNFirebaseAsStaticFramework = true
# Override Firebase SDK Version
$FirebaseSDKVersion = '10.22.0'


#target里面添加
pod 'FirebaseCore', :modular_headers => true
pod 'FirebaseCoreInternal', :modular_headers => true
pod 'GoogleUtilities', :modular_headers => true

以上是需要添加的原生代码的步骤

2、在react-native的项目的根目录创建firebase.json文件,代码如下:

{
  "react-native": {
    "android_task_executor_maximum_pool_size": 10,
    "android_task_executor_keep_alive_seconds": 3,
    "messaging_ios_auto_register_for_remote_messages": true
    
    // "crashlytics_debug_enabled": true,
    // "crashlytics_disable_auto_disabler": true,
    // "crashlytics_auto_collection_enabled": true,
    // "crashlytics_is_error_generation_on_js_crash_enabled": true,
    // "crashlytics_javascript_exception_handler_chaining_enabled": true
  }
}

3、获取token、接收前后台消息

/**
 * 获取firebase的token
 */
export function getFireBaseToken() {
  messaging().getToken().then(token => {
    console.log("===== getFireBaseToken token =====", token)
  }).catch(error => {
    console.log("===== getFireBaseToken error =====", error)
  });
  messaging().onTokenRefresh(token => {
    console.log("===== onTokenRefresh token =====", token)
  });
}

/**
 * 监听通知消息
 */
export function getFireBaseMessage() {
  if (!subscribeOnMessage) {
    subscribeOnMessage = messaging().onMessage(async remoteMessage => {
      console.log('==== A new FCM message arrived! ====', JSON.stringify(remoteMessage))
      //ios: {"messageId":"1710141274326336","from":"369009713610","data":{},"sentTime":"1710141189","mutableContent":true,"notification":{"body":"通知文字是3月11日 15:00","title":"标题是3月11日 15:00"}}
      //android: '{"notification":{"android":{},"body":"通知文字是3月11日 15:00","title":"标题是3月11日 15:00"},"sentTime":1710141244035,"data":{},"from":"369009713610","messageId":"0:1710141303098717%0a8128d30a8128d3","ttl":604800,"collapseKey":"com.booming.booming"}'
      checkMessagePermission(() => {
        onDisplayNotification(remoteMessage);
      });
    });
  }
  //注册后台的监听消息事件
  registerBackgroundMessage();

  return subscribeOnMessage;
}

/**
 * 监听后台的通知消息(不能放在index.js,需要等待 第三方库类初始化)
 * !!!如果存在具有此notification属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。
 */
export function registerBackgroundMessage() {
  console.log("======== registerBackgroundMessage =======")
  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('==== Message handled in the background! ====', remoteMessage);
    // 如果存在具有此notification属性的传入消息,系统会弹出来通知,最好统一由notifee处理
    // checkMessagePermission(() => {
    //   onDisplayNotification(remoteMessage);
    // });
  })
}

4、通知权限的询问 ,使用了第三方库react-native-permissions

/**
 * 获取设备的app是否打开了通知权限
 */
export async function checkMessagePermission(callback, failCallback) {
  checkNotifications().then(async ({ status }) => {
    console.log("====== checkNotifications ===", status)
    if (status == 'granted') {//android权限即使是同意了,使用PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)方法,返回的是:never_ask_again
      //Android或ios已经有通知的权限
      callback && callback();
    } else {
      if (Platform.OS == 'ios') {//让ios的设置页面显示“通知”的菜单,并请求该权限
        const authorizationStatus = await messaging().requestPermission();//首次询问才有权限申请弹窗
        console.log('===== ios Permission status:', authorizationStatus);
        if (authorizationStatus) {
          //ios 已经有权限
          callback && callback();
        } else {
          // openSettings();
          failCallback && failCallback();
        }
      } else if (Platform.OS == "android") {//首次询问才有权限申请弹窗
        const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
        console.log("======== android Permission status:", result);
        if (result == 'granted') {
          //android 已经有权限
          callback && callback();
        } else {
          // openSettings();
          failCallback && failCallback();
        }
      }

    }
  }).catch(err => {
    console.log("====== checkNotifications error===", err)
  })
}

5、显示通知,我使用了@notifee/react-native库
messaging().onMessage()是App前台接收消息的事件(前台是指app页面在当前屏幕上显示,后台是指App进程杀掉,app应用退到后台,当前屏幕看不到app页面)
onMessage接收到的消息需要手动显示通知,如下:

/**
 * @param {*} remoteMessage 
 * 显示消息通知
 */
export async function onDisplayNotification(remoteMessage) {
  // const settings = await notifee.requestPermission();// Request permissions (required for iOS)
  const { notification, data } = remoteMessage;

  // Create a channel (required for Android)
  const channelId = await notifee.createChannel({
    id: 'default',
    name: 'Default Channel',
    // badge: true,
    // vibration: true,
    // vibrationPattern: [300, 500],
    // importance: AndroidImportance.HIGH,
  });

  // Display a notification
  await notifee.displayNotification({
    title: notification.title,
    body: notification.body,
    data: data,
    android: {
      channelId,
      largeIcon: 'ic_launcher',
      smallIcon: 'ic_notification', // defaults to 'ic_launcher'. 安卓5后 不允许在通知栏使用彩色图标
      // pressAction is needed if you want the notification to open the app when pressed
      pressAction: {
        id: 'default',
      },
    },
  });
}

messaging().setBackgroundMessageHandler()是后台接受消息的事件,firebase会自动显示该通知,不需要再手动弹出通知。
(官方文档写:如果存在具有此notification属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。)

5、处理点击的通知消息,注册notifee的前后台事件

/**
 * 通知前台的点击监听事件
 */
export function notifeeForegroundEvent() {
  try {
    if (!subscribeNotifeeFore) {
      //点击通知的事件
      subscribeNotifeeFore = notifee.onForegroundEvent(({ type, detail }) => {
        console.log("==== onForegroundEvent =====type:" + type, detail)
        //{"notification": {"body": "通知文字是3月12日 12:00", "data": {"id": "271", "pageName": "MerchantTaskDetailPage"}, "id": "5fdeT8yJgHvCiVnAJQGf"}
        switch (type) {
          case EventType.DISMISSED:
            console.log('User dismissed notification', detail.notification);
            break;
          case EventType.PRESS:
            console.log('User pressed notification', detail.notification);
            processNotification(detail.notification);
            break;
        }
      });
    }
  } catch (error) {
    console.log("===== notifeeForegroundEvent error ->", error);
  }

  return subscribeNotifeeFore;
}

/**
 * 通知后台的点击事件(不能放在index.js,需要等待 第三方库类初始化)
 */
export function notifeeBackgroundEvent() {
  console.log("====== notifeeBackgroundEvent init =======")
  try {
    notifee.onBackgroundEvent(async ({ type, detail }) => {
      const { notification } = detail;
      console.log("====== notifeeBackgroundEvent =====type:" + type, detail);

      // Check if the user pressed the "Mark as read" action
      // if (type === EventType.ACTION_PRESS) {// && pressAction.id === 'mark-as-read'
      // Remove the notification
      // await notifee.cancelNotification(notification.id);
      // }
      switch (type) {
        case EventType.DISMISSED:
          console.log('User dismissed notification', detail.notification);
          break;
        case EventType.PRESS:
          console.log('User pressed notification', detail.notification);
          // if (Platform.OS == 'ios') {//Android的后台消息处理在 messaging().getInitialNotification()方法调用后
          // processNotification(detail.notification);
          // }
          await notifee.decrementBadgeCount();
          await notifee.cancelNotification(notification.id);
          break;
      }
    });
  } catch (error) {
    console.log("===== notifeeBackgroundEvent error ->", error);
  }

}

注意,根据app应用的前后台的状态不一样,事件处理也不同的。
(1)、app进程杀掉,点击通知,
iOS会转为notifeeForegroundEvent事件;
android的messaging().getInitialNotification()和messaging().onNotificationOpenedApp的方法来获取该通知数据
(2)、app在后台,点击通知,
iOS会转为notifeeForegroundEvent事件;
android走notifeeBackgroundEvent事件;
(3)、app在前台,ios和android走notifeeForegroundEvent事件

6、部分方法需要放在index.js里面执行,

import "react-native-gesture-handler";
import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { notifeeBackgroundEvent, registerBackgroundMessage } from "./src/business/FirebaseMessageBusiness";

//在FirebaseMessageBusiness会再次调用,防止事件注册不上
registerBackgroundMessage();
notifeeBackgroundEvent();

AppRegistry.registerComponent(appName, () => App);

FirebaseMessageBusiness 文件的完整代码如下:

import messaging from '@react-native-firebase/messaging';
import { PermissionsAndroid, Platform } from 'react-native';
import { checkNotifications, openSettings } from 'react-native-permissions';
import notifee, { EventType } from '@notifee/react-native';
import { NavigationService } from '../utils/All';
import appModel from '../model/AppModel';

let subscribeOnMessage = null;//消息监听事件
let subscribeNotifeeFore = null;//通知点击监听事件
let subscribeOnNotifyOpened = null;

//初始化
export async function initFireBaseMessage() {
  try {
    if (Platform.OS == 'android') {//ios的后台消息都会转为notifeeForegroundEvent事件去接收
      //getInitialNotification: When the application is opened from a quit state.
      const remotMessage = await messaging().getInitialNotification();
      console.log("======= android remotMessage =====" + JSON.stringify(remotMessage));
      if (remotMessage) {
        processNotification(remotMessage);
      }

      if (!subscribeOnNotifyOpened) {
        // onNotificationOpenedApp: When the application is running, but in the background.由系统弹出来的通知消息,点击该通知会触发这个方法
        //(场景一般是android应用在后台的时候,有message触发setBackgroundMessageHandler方法,系统会弹出来通知)
        subscribeOnNotifyOpened = messaging().onNotificationOpenedApp((message) => {
          console.log("=======android onNotificationOpenedApp =====" + JSON.stringify(message));
          if (message) {
            processNotification(message);
          }
        });
      }
    }
  } catch (error) {
    console.log("====== initFireBaseMessage ===", error)
  }

  getFireBaseToken();
  getFireBaseMessage();
  notifeeForegroundEvent();
  //注册通知的后台事件,https://notifee.app/react-native/docs/events
  notifeeBackgroundEvent();
  checkMessagePermission(() => {
    console.log("==== initFireBaseMessage  checkMessagePermission ====")
  });
}

//移除所有的事件
export function removeMsgSubscribe() {
  if (subscribeOnMessage) {
    subscribeOnMessage();
  }
  if (subscribeNotifeeFore) {
    subscribeNotifeeFore();
  }
  if (subscribeOnNotifyOpened) {
    subscribeOnNotifyOpened();
  }
}

/**
 * 获取firebase的token
 */
export function getFireBaseToken() {
  messaging().getToken().then(token => {
    console.log("===== getFireBaseToken token =====", token)
  }).catch(error => {
    console.log("===== getFireBaseToken error =====", error)
  });
  messaging().onTokenRefresh(token => {
    console.log("===== onTokenRefresh token =====", token)
  });
}

/**
 * 监听通知消息
 */
export function getFireBaseMessage() {
  if (!subscribeOnMessage) {
    subscribeOnMessage = messaging().onMessage(async remoteMessage => {
      console.log('==== A new FCM message arrived! ====', JSON.stringify(remoteMessage))
      //ios: {"messageId":"1710141274326336","from":"369009713610","data":{},"sentTime":"1710141189","mutableContent":true,"notification":{"body":"通知文字是3月11日 15:00","title":"标题是3月11日 15:00"}}
      //android: '{"notification":{"android":{},"body":"通知文字是3月11日 15:00","title":"标题是3月11日 15:00"},"sentTime":1710141244035,"data":{},"from":"369009713610","messageId":"0:1710141303098717%0a8128d30a8128d3","ttl":604800,"collapseKey":"com.booming.booming"}'
      checkMessagePermission(() => {
        onDisplayNotification(remoteMessage);
      });
    });
  }
  //注册后台的监听消息事件
  registerBackgroundMessage();

  return subscribeOnMessage;
}

/**
 * 监听后台的通知消息(不能放在index.js,需要等待 第三方库类初始化)
 * !!!如果存在具有此notification属性的传入消息,并且应用程序当前不可见(退出或在后台),则会在设备上显示通知。但是,如果应用程序位于前台,则将传递包含通知数据的事件,并且不会显示可见的通知。
 */
export function registerBackgroundMessage() {
  console.log("======== registerBackgroundMessage =======")
  messaging().setBackgroundMessageHandler(async (remoteMessage) => {
    console.log('==== Message handled in the background! ====', remoteMessage);
    // 如果存在具有此notification属性的传入消息,系统会弹出来通知,最好统一由notifee处理
    // checkMessagePermission(() => {
    //   onDisplayNotification(remoteMessage);
    // });
  })
}

/**
 * 获取设备的app是否打开了通知权限
 */
export async function checkMessagePermission(callback, failCallback) {
  checkNotifications().then(async ({ status }) => {
    console.log("====== checkNotifications ===", status)
    if (status == 'granted') {//android权限即使是同意了,使用PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS)方法,返回的是:never_ask_again
      //Android或ios已经有通知的权限
      callback && callback();
    } else {
      if (Platform.OS == 'ios') {//让ios的设置页面显示“通知”的菜单,并请求该权限
        const authorizationStatus = await messaging().requestPermission();//首次询问才有权限申请弹窗
        console.log('===== ios Permission status:', authorizationStatus);
        if (authorizationStatus) {
          //ios 已经有权限
          callback && callback();
        } else {
          // openSettings();
          failCallback && failCallback();
        }
      } else if (Platform.OS == "android") {//首次询问才有权限申请弹窗
        const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
        console.log("======== android Permission status:", result);
        if (result == 'granted') {
          //android 已经有权限
          callback && callback();
        } else {
          // openSettings();
          failCallback && failCallback();
        }
      }

    }
  }).catch(err => {
    console.log("====== checkNotifications error===", err)
  })
}

/**
 * 通知前台的点击监听事件
 */
export function notifeeForegroundEvent() {
  try {
    if (!subscribeNotifeeFore) {
      //点击通知的事件
      subscribeNotifeeFore = notifee.onForegroundEvent(({ type, detail }) => {
        console.log("==== onForegroundEvent =====type:" + type, detail)
        //{"notification": {"body": "通知文字是3月12日 12:00", "data": {"id": "271", "pageName": "MerchantTaskDetailPage"}, "id": "5fdeT8yJgHvCiVnAJQGf"}
        switch (type) {
          case EventType.DISMISSED:
            console.log('User dismissed notification', detail.notification);
            break;
          case EventType.PRESS:
            console.log('User pressed notification', detail.notification);
            processNotification(detail.notification);
            break;
        }
      });
    }
  } catch (error) {
    console.log("===== notifeeForegroundEvent error ->", error);
  }

  return subscribeNotifeeFore;
}

/**
 * 通知后台的点击事件(不能放在index.js,需要等待 第三方库类初始化)
 */
export function notifeeBackgroundEvent() {
  console.log("====== notifeeBackgroundEvent init =======")
  try {
    notifee.onBackgroundEvent(async ({ type, detail }) => {
      const { notification } = detail;
      console.log("====== notifeeBackgroundEvent =====type:" + type, detail);

      // Check if the user pressed the "Mark as read" action
      // if (type === EventType.ACTION_PRESS) {// && pressAction.id === 'mark-as-read'
      // Remove the notification
      // await notifee.cancelNotification(notification.id);
      // }
      switch (type) {
        case EventType.DISMISSED:
          console.log('User dismissed notification', detail.notification);
          break;
        case EventType.PRESS:
          console.log('User pressed notification', detail.notification);
          // if (Platform.OS == 'ios') {//Android的后台消息处理在 messaging().getInitialNotification()方法调用后
          // processNotification(detail.notification);
          // }
          await notifee.decrementBadgeCount();
          await notifee.cancelNotification(notification.id);
          break;
      }
    });
  } catch (error) {
    console.log("===== notifeeBackgroundEvent error ->", error);
  }

}

/**
 * 处理消息
 */
export function processNotification(notification) {
  try {
    const dataObj = notification.data;
    console.log("====== dataObj ===notification:", JSON.stringify(notification), dataObj)
    console.log('appModel.isShowSplash: ', appModel.isShowSplash);
    if (appModel.isShowSplash) {
      NavigationService.navigate(dataObj.pageName, { ...dataObj });
    } else {
      appModel.setNoticeInfo(dataObj)
    }
  } catch (error) {
    console.log("==== processNotification error!", error)
  }
}

/**
 * @param {*} remoteMessage 
 * 显示消息通知
 */
export async function onDisplayNotification(remoteMessage) {
  // const settings = await notifee.requestPermission();// Request permissions (required for iOS)
  const { notification, data } = remoteMessage;

  // Create a channel (required for Android)
  const channelId = await notifee.createChannel({
    id: 'default',
    name: 'Default Channel',
    // badge: true,
    // vibration: true,
    // vibrationPattern: [300, 500],
    // importance: AndroidImportance.HIGH,
  });

  // Display a notification
  await notifee.displayNotification({
    title: notification.title,
    body: notification.body,
    data: data,
    android: {
      channelId,
      largeIcon: 'ic_launcher',
      smallIcon: 'ic_notification', // defaults to 'ic_launcher'. 安卓5后 不允许在通知栏使用彩色图标
      // pressAction is needed if you want the notification to open the app when pressed
      pressAction: {
        id: 'default',
      },
    },
  });
}
上一篇 下一篇

猜你喜欢

热点阅读