You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic6+Capacitor+Angular iOS端pushNotificationReceived仅前台触发问题

解决Ionic 6 + Capacitor + Angular iOS推送通知后台事件不触发问题

问题背景

使用Ionic 6、Capacitor和Angular开发的应用,在iPhone上实现推送通知时遇到以下问题:

  • 应用前台和后台均能收到通知,但pushNotificationReceived事件仅在前台状态下触发
  • 后台状态下无法通过该事件更新应用角标计数

用户代码示例:

await PushNotifications.addListener('pushNotificationReceived', async (notification: PushNotificationSchema) => {
      // update the app badge count
      const badgeCount = await this.getDeliveredNotifications();
      if (!badgeCount || badgeCount == 0) Badge.set({ count: 1 });
      else Badge.set({ count: badgeCount });
    });

private getDeliveredNotifications = async () => {
    const notificationList: DeliveredNotifications = await PushNotifications.getDeliveredNotifications();
    console.log('delivered notifications', notificationList);
    return notificationList.notifications.length;
  }

解决方案

1. 明确Capacitor推送事件的触发逻辑

Capacitor的pushNotificationReceived仅在应用前台接收通知时触发。针对后台场景,需要分两种情况处理:

  • 用户点击后台通知唤醒应用:监听pushNotificationActionPerformed事件
  • 后台静默处理通知(无需用户点击):需配置静默推送并确保后台权限开启

2. 配置iOS后台推送权限

  • 打开Xcode项目,进入Signing & Capabilities,添加Background Modes,勾选Remote notifications
  • 推送payload必须包含content-available: 1(数字类型),示例:
{
  "aps": {
    "alert": "新通知内容",
    "badge": 1,
    "sound": "default",
    "content-available": 1
  }
}

3. 调整代码监听对应事件

修改代码,覆盖前台、后台点击、静默推送三种场景:

// 前台接收通知
await PushNotifications.addListener('pushNotificationReceived', async (notification: PushNotificationSchema) => {
  await this.updateBadgeCount();
});

// 用户点击后台通知唤醒应用
await PushNotifications.addListener('pushNotificationActionPerformed', async () => {
  await this.updateBadgeCount();
});

// 后台静默推送处理(依赖payload的content-available字段)
await PushNotifications.addListener('pushNotificationReceived', async (notification: PushNotificationSchema) => {
  if (notification.data?.['content-available'] === 1) {
    await this.updateBadgeCount();
  }
});

// 统一的角标更新方法
private async updateBadgeCount() {
  const { notifications } = await PushNotifications.getDeliveredNotifications();
  const count = notifications.length;
  await Badge.set({ count: count || 1 });
}

4. 验证依赖版本兼容性

确保Capacitor核心和推送插件版本兼容,执行以下命令更新:

npm update @capacitor/core @capacitor/push-notifications
npx cap sync ios

5. 检查iOS系统通知设置

  • 确认应用已获得通知权限:设置 > 通知 > 你的应用中开启允许通知
  • 开启后台刷新:设置 > 通用 > 后台App刷新中启用对应应用

内容的提问来源于stack exchange,提问作者Chandra T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 11:42:06