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

请求指导:基于React Native实现Android和iOS跨平台推送通知

Hey there! Let's walk through how to set up push notifications for both Android and iOS in React Native step by step. I'll break it down clearly so you can follow along easily. We'll use @react-native-firebase/messaging for this setup—it's the most reliable, officially maintained library for cross-platform push in React Native.


1. Pre-requisites & Library Setup

First, make sure you have:

  • A React Native project (v0.60+ recommended, since autolinking works seamlessly here)
  • A Firebase account (we'll use Firebase Cloud Messaging, FCM, to handle push relay across platforms)

Install the required packages

Run these commands in your project root:

# Install the messaging core package
npm install @react-native-firebase/messaging
# Or using yarn
yarn add @react-native-firebase/messaging

# For iOS, install CocoaPods dependencies
cd ios && pod install && cd ..

You'll also need to link Firebase to each platform—we'll cover that in the platform-specific sections below.


2. iOS Platform Configuration

iOS has stricter push requirements, so let's tackle this first:

Step 1: Enable Push Notifications in Apple Developer Portal

  • Log into your Apple Developer Account
  • Navigate to your App ID, then enable Push Notifications
  • Create either an APNs Certificate (for development/production environments) or an APNs Auth Key (recommended, works for both environments)
  • Add this credential to your Firebase project's iOS app settings (under the "Cloud Messaging" tab)

Step 2: Xcode Project Setup

  • Open your project in Xcode (ios/YourProject.xcworkspace)
  • Go to your target's Signing & Capabilities tab:
    • Click "+ Capability" and add Push Notifications
    • Add Background Modes capability, then check "Remote notifications"
  • Update your Info.plist to add notification permission descriptions (required for iOS 10+):
    <key>NSUserNotificationUsageDescription</key>
    <string>We need permission to send you important updates and alerts</string>
    <key>NSAlertUsageDescription</key>
    <string>We need permission to show you alert notifications</string>
    

Step 3: iOS Code Implementation

First, request user permission for notifications:

import messaging from '@react-native-firebase/messaging';

async function requestPushPermission() {
  const authStatus = await messaging().requestPermission({
    alert: true,
    badge: true,
    sound: true,
  });
  const isEnabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (isEnabled) {
    console.log('Notification authorization granted:', authStatus);
    await getFCMToken(); // Fetch token once permission is approved
  }
}

Then get the FCM token to send push notifications to:

async function getFCMToken() {
  const token = await messaging().getToken();
  console.log('FCM Token (iOS):', token);
  // Send this token to your backend to store for targeted pushes
}

Handle notification reception scenarios:

  • Foreground notifications: iOS won't show native alerts by default when the app is active. You can customize this with a library like react-native-push-notification or build a custom alert:
    messaging().onMessage(async remoteMessage => {
      console.log('Received foreground notification:', remoteMessage);
      // Add your custom alert logic here
    });
    
  • Background/killed app notifications: These are handled by FCM automatically, but you can listen for tap events:
    // Triggered when app is in background and notification is tapped
    messaging().onNotificationOpenedApp(remoteMessage => {
      console.log('Notification opened from background:', remoteMessage);
      // Navigate to relevant screen based on notification data
    });
    
    // Check if app was opened from a terminated state via notification
    messaging()
      .getInitialNotification()
      .then(remoteMessage => {
        if (remoteMessage) {
          console.log('App opened from terminated state:', remoteMessage);
        }
      });
    

3. Android Platform Configuration

Android setup is more straightforward, but there are a few key steps:

Step 1: Firebase Project Setup

  • Go to the Firebase Console, create an Android app for your project
  • Download the google-services.json file and place it in your project's android/app/ directory

Step 2: Gradle Configuration

  • In android/build.gradle, add the Google services plugin dependency:
    buildscript {
      dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.15'
      }
    }
    
  • In android/app/build.gradle, apply the plugin at the bottom of the file:
    // Add this line at the end
    apply plugin: 'com.google.gms.google-services'
    

Step 3: AndroidManifest Setup

Add required permissions and service declarations (replace com.yourpackage with your actual app package name):

<!-- Basic permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <!-- Required for Android 13+ -->

<!-- FCM Messaging Service -->
<service
  android:name="io.invertase.firebase.messaging.ReactNativeFirebaseMessagingService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>

Step 4: Android Code Implementation

Request notification permissions (critical for Android 13+):

import messaging from '@react-native-firebase/messaging';
import { Platform, PermissionsAndroid } from 'react-native';

async function requestPushPermission() {
  if (Platform.OS === 'android') {
    // Request base notification permissions
    await messaging().requestPermission({
      alert: true,
      badge: true,
      sound: true,
    });
    // Separate permission for Android 13+
    await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
  } else {
    // Reuse the iOS permission logic we wrote earlier
    const authStatus = await messaging().requestPermission({
      alert: true,
      badge: true,
      sound: true,
    });
    const isEnabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;
    if (isEnabled) await getFCMToken();
  }
}

Handle notifications similar to iOS:

// Foreground notifications
messaging().onMessage(remoteMessage => {
  console.log('Foreground notification (Android):', remoteMessage);
  // Show custom notification if needed
});

// Background tap handling
messaging().onNotificationOpenedApp(remoteMessage => {
  console.log('Notification tapped in background:', remoteMessage);
});

// Terminated state tap handling
messaging().getInitialNotification().then(remoteMessage => {
  if (remoteMessage) {
    console.log('App opened from terminated via notification:', remoteMessage);
  }
});

4. Key Notes & Troubleshooting
  • iOS Testing: You can't test push notifications on iOS simulators—use a physical device.
  • Token Refreshes: FCM tokens can expire or change, so listen for refresh events to update your backend:
    messaging().onTokenRefresh(newToken => {
      console.log('Token refreshed:', newToken);
      // Update this new token on your backend
    });
    
  • Silent Data Handling: If you need to process notification data without showing an alert, set up a background handler: use a headless JS task for Android, and enable "Content & Privacy" background mode plus FCM data messages for iOS.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:35:28