如何自定义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
alertfield (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

