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

如何在推送通知中传递参数,实现APP打开指定ID的特定表单并展示对应数据

Hey there! Great question—this is a super common use case for push notifications, and there are solid ways to pull this off without relying on user tags. The core idea is to embed your custom parameters directly into the push notification payload, then have your app listen for notification taps, parse those parameters, and trigger the correct form navigation. Let me break down the implementation for you:

Core Approach

All major push services (APNs for iOS, FCM for Android) support adding custom key-value pairs to the notification payload. These values are hidden from the user in the notification UI but are accessible to your app when the user taps the notification. You can include parameters like form_id, data_id, or any other identifiers your app needs to load the right content.

Platform-Specific Implementation

iOS (APNs)

When sending the push notification, add your custom parameters outside the aps dictionary in the payload:

{
  "aps": {
    "alert": {
      "title": "New Form Available",
      "body": "Tap to view your form"
    },
    "sound": "default"
  },
  "form_id": "12345",
  "data_id": "67890"
}

Then, in your app code, handle the notification tap to extract the parameters and navigate:

// In your SceneDelegate (iOS 13+) or AppDelegate
import UserNotifications

class SceneDelegate: UIResponder, UIWindowSceneDelegate, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        // Extract custom parameters from the notification payload
        let userInfo = response.notification.request.content.userInfo
        guard let formId = userInfo["form_id"] as? String else {
            completionHandler()
            return
        }
        
        // Navigate to the form screen with the extracted ID
        let formVC = FormViewController()
        formVC.targetFormId = formId
        
        // Handle navigation based on your app's structure
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let rootNavVC = windowScene.windows.first?.rootViewController as? UINavigationController {
            rootNavVC.pushViewController(formVC, animated: true)
        }
        
        completionHandler()
    }
}

Android (FCM)

For Android, add your custom parameters in the data field of the FCM payload:

{
  "notification": {
    "title": "New Form Available",
    "body": "Tap to view your form"
  },
  "data": {
    "form_id": "12345",
    "data_id": "67890"
  },
  "to": "USER_FCM_TOKEN"
}

Then, handle the notification tap and pass parameters to your form activity:

// In your FirebaseMessagingService subclass
class MyMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        remoteMessage.data["form_id"]?.let { formId ->
            // Create a notification that navigates to the form activity
            val intent = Intent(this, FormActivity::class.java).apply {
                putExtra("FORM_ID", formId)
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
            }
            val pendingIntent = PendingIntent.getActivity(
                this,
                0,
                intent,
                PendingIntent.FLAG_IMMUTABLE
            )

            val notification = NotificationCompat.Builder(this, "FORM_NOTIFICATIONS")
                .setContentTitle("New Form Available")
                .setContentText("Tap to view your form")
                .setSmallIcon(R.drawable.ic_form_notification)
                .setContentIntent(pendingIntent)
                .build()

            NotificationManagerCompat.from(this).notify(1, notification)
        }
    }
}

Then in your FormActivity, load the data using the passed parameter:

class FormActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_form)
        
        intent.getStringExtra("FORM_ID")?.let { formId ->
            // Fetch and display data for this form ID
            loadFormData(formId)
        }
    }

    private fun loadFormData(formId: String) {
        // Your API call or local data fetch logic here
    }
}
Cross-Platform Example (React Native)

If you're using a cross-platform framework like React Native, libraries like @react-native-firebase/messaging simplify handling this:

import messaging from '@react-native-firebase/messaging';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

// Handle notification taps when app is in foreground/background
messaging().onNotificationOpenedApp(remoteMessage => {
  const formId = remoteMessage.data.form_id;
  // Navigate to form screen using your navigation library
  navigation.navigate('FormScreen', { formId });
});

// Handle app opened from quit state
messaging().getInitialNotification().then(remoteMessage => {
  if (remoteMessage) {
    const formId = remoteMessage.data.form_id;
    navigation.navigate('FormScreen', { formId });
  }
});
Key Things to Remember
  • Payload Limits: Keep your custom parameters concise—APNs limits payloads to 4KB, FCM limits notification payloads to 4KB and data payloads to 10KB.
  • State Handling: Make sure to test all app states (foreground, background, fully closed) to ensure the navigation works consistently.
  • Security: Avoid sensitive data in the payload—if you need to load private data, use the parameters to fetch it securely from your backend after the app opens.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:44:07