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

React Native iOS端如何使用Notifee将本地图片作为通知附件发送

React Native iOS端如何使用Notifee将本地图片作为通知附件发送

嘿,我之前在做React Native iOS端的通知功能时,刚好踩过本地图片作为附件的坑,结合你给出的代码片段,给你整理一套能跑通的完整方案:

一、先处理图片路径(核心坑点!)

iOS有严格的沙箱机制,APP主进程的临时目录文件,通知进程是访问不到的——这就是很多人直接用相机选择的临时路径却显示不出图片的原因。所以第一步得把选中的图片复制到通知进程能访问的目录,比如Documents目录。

给你补全并优化你现有的路径处理代码:

import RNFS from 'react-native-fs';
import notifee from '@notifee/react-native';

// 专门处理通知图片的工具函数
const prepareNotificationImage = async (asset) => {
  const localUri = asset.uri;
  if (!localUri) {
    console.warn('没找到图片的本地路径哦');
    return null;
  }

  // 提取图片后缀,默认用jpg
  const ext = asset.fileName?.split('.').pop() || 'jpg';
  // 生成唯一的目标路径,避免重名覆盖
  const targetPath = `${RNFS.DocumentDirectoryPath}/notify_attach_${Date.now()}.${ext}`;

  try {
    // 把临时路径的图片复制到Documents目录
    await RNFS.copyFile(localUri, targetPath);
    // 返回处理后的路径,后面要加file://前缀给Notifee用
    return targetPath;
  } catch (err) {
    console.error('复制图片失败:', err);
    return null;
  }
};

二、创建并发送带图片附件的通知

处理好图片路径后,就可以用Notifee创建通知了,重点是在iOS配置里添加attachments字段:

const sendImageNotification = async (selectedAsset) => {
  // 第一步:先申请通知权限,iOS必须要用户授权
  const permission = await notifee.requestPermission({
    alert: true,
    sound: true,
    badge: false,
  });

  if (!permission.alert) {
    console.warn('用户没开通知权限哦,发不了通知');
    return;
  }

  // 第二步:准备通知用的图片路径
  const imagePath = await prepareNotificationImage(selectedAsset);
  if (!imagePath) return;

  // 第三步:创建通知
  await notifee.createNotification({
    title: '你有新的图片通知',
    body: '点击查看详情',
    ios: {
      // 配置图片附件
      attachments: [
        {
          url: `file://${imagePath}`, // iOS必须加file://前缀!
          thumbnailHidden: false, // 显示图片缩略图
          // 可选:设置缩略图裁剪模式,比如'cover'或者'contain'
          thumbnailClippingStyle: 'cover',
        },
      ],
      sound: 'default',
      badgeCount: 0,
    },
  });

  // 第四步:立即显示通知
  await notifee.displayNotification();
};

三、必须注意的几个细节

  • 图片清理:复制到Documents目录的图片不会自动删除,建议在APP启动或者用户删除通知时,清理掉旧的通知附件,避免占用存储空间。
  • 格式支持:iOS通知附件只支持jpg、png、gif这些常见格式,别用太冷门的格式,不然加载不出来。
  • 路径前缀:千万别忘了加file://,Notifee靠这个识别是本地文件,不是网络链接。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 13:58:19