setBackgroundMessageHandler 在终止状态 IOS 下不会被调用

问题描述 投票:0回答:1

我在我的react-native应用程序中使用firebase/messaging来接收来自firebase的通知。

收到消息后,我将处理数据并更新我的徽章计数。在 Android 设备上,一切在前台、后台和终止状态下都能完美运行。在iOS中,前台和后台工作正常。当应用程序终止/退出,并且任何其他应用程序在前台运行时。我收到通知,但 firebase setBackgroundMessageHandler 事件未调用。我已经在通知负载中添加了 'content-available' : true ,但当另一个应用程序处于前台状态时,不会调用该事件。当我打开应用程序时,会调用 setBackgroundMessageEvent 并在应用程序中收到另一条重复消息。

请帮我解决这个问题。感谢您的每一次帮助。

ios firebase react-native push-notification firebase-cloud-messaging
1个回答
0
投票

我现在明白这个问题了。您似乎面临着在 iOS 上处理处于终止状态的通知的挑战,特别是与使用适当的 APN 标头和内容可用标志发送“仅数据”消息以触发后台处理程序有关。

如果您希望在终止或终止状态下收到通知时执行任务或进行 API 调用,则应考虑发送两个单独的通知。第一个通知应包含带有通知部分的有效负载,确保即使应用程序处于后台或终止状态,它也会触发 iOS 的通知弹出窗口。第二个通知将是“仅数据”消息,它必须包含必要的 APN 标头以及内容可用标志。此配置对于激活后台处理程序至关重要。

例如,当使用 Node.js firebase-admin 包向 iOS 设备发送“仅数据”消息时,请确保相应地构建有效负载。这种方法允许您实现在应用程序处于后台或终止状态时显示通知并触发后台处理程序进行进一步处理的所需行为。

注意有效负载结构的细节至关重要,包括可用内容和必要的 APN 标头的使用,以确保功能正常。建议在不同场景(包括前台、后台和终止状态)中进行测试,以验证您的实现是否按预期运行。

import messaging from '@react-native-firebase/messaging';
import React, { useEffect } from 'react';
import { AppRegistry, AppState } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
messaging().setBackgroundMessageHandler(async (remoteMessage) => {
  console.log('====================================');
  console.log({ 'in kill state': remoteMessage });
  // api call for status update
// you can perform you desired task
});
function HeadlessCheck({ isHeadless }) {
  console.log('background is called', isHeadless);
  if (isHeadless) {
    // App has been launched in the background by iOS, ignore
    return <FakeView />;
  }

  return <App />;
}

const FakeView = () => {
  return null;
};

AppRegistry.registerComponent(appName, () => App);
// Register the Headless task
AppRegistry.registerHeadlessTask(
  'RNFirebaseBackgroundMessage',
  () => HeadlessCheck,
);

这是我从服务器发送的有效负载:

    const message = {
    notification: {
    title: title,
    body: body,
  },
  data: { campaignId: campaignId, title: title, body: body },
  token: registrationId,
  android: {
    priority: 'high',
    notification: {
      title: title,
      body: body,
      sound: 'default',
    },
  },
  apns: {
    payload: {
      aps: {
        sound: 'default',
        'content-available': 1,
      },
    },
    headers: {
      'apns-priority': '5',
    },
  },
};
© www.soinside.com 2019 - 2024. All rights reserved.