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

Swift无法向文件写入数据求助:react-native-fs路径写入失败

解决文件写入失败的问题

问题分析

你当前代码在文件不存在时使用FileHandle(forWritingTo:)会直接报错,因为这个API仅适用于已存在的文件;同时目标路径的上级目录可能未创建,也是导致写入失败的原因。另外,用URL(string:)处理本地文件路径本身就不合适,必须使用URL(fileURLWithPath:)。

修复后的代码

do {
    let fileUrl = URL(fileURLWithPath: fileUri)
    // 先确保目标文件的上级目录存在
    let directoryUrl = fileUrl.deletingLastPathComponent()
    try FileManager.default.createDirectory(at: directoryUrl, withIntermediateDirectories: true)
    
    if FileManager.default.fileExists(atPath: fileUrl.path) {
        // 文件已存在,直接覆盖写入
        try decryptedData.write(to: fileUrl, options: .atomic)
    } else {
        // 文件不存在,写入新文件
        try data.write(to: fileUrl, options: .atomic)
    }
} catch {
    reject("FileError", "写入文件失败:\(error.localizedDescription)", error)
}

关键修改点

  • 移除FileHandle的使用:Data.write(to:)既支持创建新文件,也能覆盖已有文件,无需分开处理
  • 新增目录创建逻辑:调用createDirectory(withIntermediateDirectories: true)确保所有上级目录都被创建,避免因目录不存在报错
  • 统一使用URL(fileURLWithPath:)处理本地路径,避免URL(string:)解析本地路径的潜在问题
  • 添加.atomic写入选项:保证写入操作的原子性,防止文件损坏

简化版代码(无需区分文件是否存在)

如果decryptedData和data是同一份数据,可直接省略文件存在判断:

do {
    let fileUrl = URL(fileURLWithPath: fileUri)
    let directoryUrl = fileUrl.deletingLastPathComponent()
    try FileManager.default.createDirectory(at: directoryUrl, withIntermediateDirectories: true)
    try decryptedData.write(to: fileUrl, options: .atomic)
} catch {
    reject("FileError", "写入文件失败:\(error.localizedDescription)", error)
}

内容的提问来源于stack exchange,提问作者Kim Mỹ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 11:25:37