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

Firebase消息添加深度链接:React Native iOS端API选择及实现咨询

解决React Native iOS推送通知跳转特定页面的问题

针对你的需求,在iOS设备上实现点击Firebase推送通知跳转到应用特定页面,需要结合setApnsConfig和React Native端的通知事件监听,setFcmOptions可作为辅助配置,具体方案如下:

1. 后端配置(Firebase Admin SDK)

核心:通过ApnsConfig嵌入深度链接数据

iOS系统依赖APNs的payload处理通知行为,因此必须在ApnsConfig中添加自定义深度链接字段,确保React Native端能获取到跳转目标:

// 构建APNs配置
ApnsConfig apnsConfig = ApnsConfig.builder()
    .setAps(Aps.builder()
        .setAlert(ApsAlert.builder()
            .setTitle("新消息提醒")
            .setBody("点击查看详情")
            .build())
        .setMutableContent(true) // 允许通知扩展处理(可选,如需富媒体通知则开启)
        .build())
    // 添加自定义深度链接字段,字段名可自定义
    .putCustomData("deep_link", "myapp://product/detail/123")
    .build();

// 构建Message并配置APNs
Message message = Message.builder()
    .setToken("DEVICE_FCM_TOKEN")
    .setApnsConfig(apnsConfig)
    // 可选:配置FcmOptions的link字段(适用于Universal Links场景)
    .setFcmOptions(FcmOptions.builder().setLink("myapp://product/detail/123").build())
    .build();

// 发送消息
FirebaseMessaging.getInstance().send(message);

关于setFcmOptions的作用

setFcmOptions的link字段主要用于支持Universal Links的场景:如果你的应用已配置Universal Links(如https://yourdomain.com/product/123),设置该字段后,iOS系统会直接触发Universal Links跳转。但如果使用自定义Scheme(如myapp://),该字段无法直接生效,仍需依赖ApnsConfig的自定义字段配合React Native端处理。

2. React Native端处理跳转逻辑

使用@react-native-firebase/messaging库监听通知点击事件,获取后端传入的深度链接并执行页面跳转:

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

const Stack = createStackNavigator();

function App() {
  const navigationRef = useNavigationContainerRef();

  // 应用处于后台时点击通知的处理
  messaging().onNotificationOpenedApp(remoteMessage => {
    const deepLink = remoteMessage.data.deep_link;
    if (deepLink) {
      // 方式1:使用React Navigation直接跳转
      navigationRef.current?.navigate('ProductDetail', { id: 123 });
      // 方式2:通过Linking打开深度链接(需提前配置Scheme)
      // Linking.openURL(deepLink);
    }
  });

  // 应用未启动时点击通知的处理
  messaging().getInitialNotification().then(remoteMessage => {
    if (remoteMessage?.data?.deep_link) {
      Linking.openURL(remoteMessage.data.deep_link);
    }
  });

  return (
    <NavigationContainer ref={navigationRef}>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="ProductDetail" component={ProductDetailScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

3. 必要的iOS配置

确保你的应用已配置对应的深度链接支持:

  • 自定义Scheme:在Info.plist中添加CFBundleURLSchemes数组,包含你的Scheme(如myapp)。
  • Universal Links:如果使用,需在Apple Developer后台配置关联域名,并在服务器放置apple-app-site-association文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:06:17