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

如何自定义PushNotificationIOS?实现按需触发本地通知

How to Disable Automatic Local Notifications & Implement Custom Display with PushNotificationIOS

Got it, let's sort this out for you—you want full control over how your remote notifications show up instead of letting the system auto-pop them. Here's a step-by-step solution tailored to your setup:

1. Tweak iOS Native Code (AppDelegate)

First, we need to stop the system from automatically displaying remote notifications. This requires adjusting your AppDelegate file (either Objective-C or Swift):

Objective-C (AppDelegate.m)

Find the remote notification handling methods and update them to skip the default system behavior, then pass the notification data to React Native:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
  // Don't call super—this prevents automatic system notifications
  // Pass the notification to React Native's PushNotificationIOS
  [[RCTPushNotificationManager sharedInstance] handleRemoteNotification:userInfo];
  
  completionHandler(UIBackgroundFetchResultNoData);
}

// For iOS 10+ background/foreground handling
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler {
  NSDictionary *userInfo = response.notification.request.content.userInfo;
  
  // Skip default handling and pass to RN
  [[RCTPushNotificationManager sharedInstance] handleNotificationResponse:response];
  
  completionHandler();
}

Swift (AppDelegate.swift)

Override the notification methods to bypass automatic system alerts:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // Don't call super to avoid auto-notifications
    RCTPushNotificationManager.shared().handleRemoteNotification(userInfo)
    completionHandler(.noData)
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    RCTPushNotificationManager.shared().handle(response)
    completionHandler()
}

2. Update React Native Code for Manual Custom Notifications

Now that the system isn't auto-showing alerts, you can use PushNotificationIOS's local notification methods to display your custom content in the listener:

import PushNotificationIOS from '@react-native-community/push-notification-ios';

// Set up your notification listener
PushNotificationIOS.addEventListener('notification', (notifIOS) => {
  // Extract custom data from the notification payload
  const notificationType = notifIOS.getData().type;
  let customAlertBody = '';

  // Define custom messages based on your notification types
  switch(notificationType) {
    case 'order_status':
      customAlertBody = `Your order #${notifIOS.getData().orderId} has been updated!`;
      break;
    case 'direct_message':
      customAlertBody = `New message from ${notifIOS.getData().senderName}`;
      break;
    default:
      customAlertBody = notifIOS.getMessage() || 'You have a new update';
  }

  // Manually trigger a local notification with your custom content
  PushNotificationIOS.presentLocalNotification({
    alertTitle: 'My App Alert',
    alertBody: customAlertBody,
    soundName: 'default', // Optional: add custom sound if needed
    badge: 1, // Optional: update app badge count
    userInfo: notifIOS.getData() // Pass through original data if needed
  });

  // Mark the notification as processed to clear it from the system
  notifIOS.finish(PushNotificationIOS.FetchResult.NoData);
});

Quick Tips

  • Ensure your remote notification payload doesn’t include an alert field (or if it does, the native override will still work—though sending only custom data keeps things cleaner).
  • Test both foreground and background scenarios: when the app is in background, the native code will still pass the notification to RN, but you might want to add logic to handle background state if needed.
  • Don’t forget to request notification permissions upfront with PushNotificationIOS.requestPermissions().

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:34:30