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

iOS前台通知场景下Cordova Push Plugin的替代方案及配置方法

解决方案:iOS前台显示系统级推送通知

一、配置现有havesource/cordova-plugin-push实现需求

虽然该插件存在未解决的公开问题,但通过以下配置和小改动可以实现iOS前台通知:

1. 初始化插件时添加presentationOptions参数

在PushNotification.init的iOS配置中,明确指定presentationOptions数组,包含需要触发的通知类型:

const push = PushNotification.init({
  android: {
    foreground: true,
    // 你的Android其他配置
  },
  ios: {
    alert: true,
    badge: true,
    sound: true,
    foreground: true,
    presentationOptions: ["alert", "badge", "sound"] // 强制前台显示弹窗、角标、声音
  }
});

该参数对应iOS原生的UNNotificationPresentationOptions,会告诉系统在前台时如何展示通知。

2. 确保权限请求包含前台通知权限

iOS 10+需要明确请求alert、sound权限,插件初始化时会自动请求,但如果之前权限请求不全,可手动触发:

PushNotification.requestPermissions({
  ios: {
    alert: true,
    badge: true,
    sound: true
  }
});

3. 插件原生代码补丁(若上述配置无效)

如果插件默认的iOS代理方法未正确处理前台通知,可修改插件的PushPlugin.m文件:
找到userNotificationCenter:willPresentNotification:withCompletionHandler:方法,修改完成回调的参数:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    // 保留原有业务逻辑代码
    // 强制触发所有通知展示选项
    completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge);
}

修改后重新编译iOS项目即可生效,建议fork插件仓库自行维护该修改,避免后续插件更新覆盖。

二、替代方案:结合本地通知插件实现

如果不想修改现有插件,可使用cordova-plugin-local-notifications配合推送插件,在前台收到推送时触发系统本地通知,实现通知中心展示和震动:

1. 安装本地通知插件

cordova plugin add cordova-plugin-local-notifications

2. 在推送通知回调中触发本地通知

push.on('notification', function(data) {
  // 判断iOS平台且处于前台
  if (device.platform === 'iOS' && data.additionalData?.foreground) {
    // 触发系统本地通知
    cordova.plugins.notification.local.schedule({
      title: data.title,
      text: data.message,
      sound: 'default',
      vibrate: true,
      badge: data.badge,
      foreground: true // 允许前台显示
    });
  }
});

这种方式利用系统本地通知能力,完全符合iOS用户设置的通知行为,会自动触发震动、声音并显示在通知中心。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 17:20:31