使用@react-native-firebase/messaging 的 iOS 后台通知处理程序问题

标签 ios react-native push-notification firebase-cloud-messaging react-native-firebase

当应用程序处于后台或关闭状态时,我面临这个问题。在所有情况下,通知都会显示在通知中心,但 messaging().setBackgroundMessageHandler 除外。不会每次都被调用,但只会在应用程序上严格检查时调用几次。遵循云消息官方文档,升级为版本 10.2.0 @react-native-firebase/messaging@react-native-firebase/app .所有状态回调在 中工作正常安卓并且每次都得到完美,问题只存在于 iOS 并且不确定是什么导致了这一切。
在此处为我正在使用的 ref 添加代码。
在入口文件中,即 index.js

messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  console.log("Message handled in the background! 1", remoteMessage);
});

function HeadlessCheck({ isHeadless }) {
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return null;
  }
  return <App />;
}

AppRegistry.registerComponent(appName, () => HeadlessCheck);
App.js:
const App = () => {
  var notif = new NotifService();
  useEffect(() => {
    requestUserPermission()
    checkPermission()
    console.log("checkPermission")

    const unsubscribe = messaging().onMessage(async remoteMessage => {
      console.log("A new FCM message arrived!: foreground: ", remoteMessage)
      console.log("A new FCM message arrived!: foreground: ", remoteMessage.messageId)
      // Alert.alert('A new FCM message arrived!: foreground: ', JSON.stringify(remoteMessage));
      notif.localNotif();
    });
  
    return unsubscribe;
  }, []);

  useEffect(() => {
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log(
        'Notification caused app to open from background state:',
        remoteMessage.notification,
      );
      Alert.alert('Message handled in the background state!', JSON.stringify(remoteMessage));
      // navigation.navigate(remoteMessage.data.type);
    });
  
    // Check whether an initial notification is available
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log(
            'Notification caused app to open from quit state:',
            remoteMessage.notification,
          );
          Alert.alert('Message handled in the quit state!', JSON.stringify(remoteMessage));
          // setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
        }
        // setLoading(false);
      });
  }, []);

  async function requestUserPermission() {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
  
    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
  }

    // 1
    async function checkPermission() {
      const enabled = await messaging().hasPermission();
      console.log("checkPermission: enabled: ", enabled)
      if (enabled) {
        getToken();
      } else {
        requestPermission();
      }
    }
  
    // 3
    async function getToken() {
      let fcmToken = await AsyncStorage.getItem('fcmToken');
      console.log('fcmToken @@1:', fcmToken);
      if (!fcmToken) {
        fcmToken = await messaging().getToken();
        console.log('fcmToken @@2:', fcmToken);
        if (fcmToken) {
          // user has a device token
          await AsyncStorage.setItem('fcmToken', fcmToken);
        }
      }
    }
  
    // 2
    async function requestPermission() {
      console.log("requestPermission:")
      try {
        await messaging().requestPermission();
        // User has authorised
        getToken();
      } catch (error) {
        // User has rejected permissions
        console.log('permission rejected');
      }
    }
}
有效载荷 我使用 firebase rest API 进行了测试:
{ "to": "TOKEN_HERE", "data": { "notification": { "title": "ABC1", "body": "xyz1" }, "Name": "121" }, "notification": { "title": "ABC1", "body": "xyz1" }, "priority": "high", "content_available": true }
如果有人遇到同样的问题并解决了这个问题,请在此处添加。现在被这个问题困了好几天!谢谢。

最佳答案

改用新的 API onBackgroundMessage

Version 7.18.0 - August 13, 2020 Cloud Messaging
Deprecated setBackgroundMessageHandler. Use the new API onBackgroundMessage instead.
https://firebase.google.com/support/release-notes/js#cloud-messaging_2

关于使用@react-native-firebase/messaging 的 iOS 后台通知处理程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65323751/

相关文章:

android - 在 React Native 中制作 slider 导航的最佳方法

android - 我如何处理 IMF8 中的推送通知?

ios - 从 NSArray 中检索对象并将每个值设置为单独的 NSString

ios - 如何在 CollectionView 中更快地加载 JSON 图像 url

android - 如何在 React Native 中实现类似 snapchat 的圆形动画倒计时组件?

android - react native 自定义字体

iphone - Apple 的 APNS 传输有时很慢

android - 仅当应用程序未运行 android 时显示推送通知

ios - 当您点击 iOS 主屏幕上的应用程序图标时,如何制作应用程序启动之类的动画?

ios - 无法打开 Promise<[CLPlacemark]>