代码之家  ›  专栏  ›  技术社区  ›  kregtopoli

尝试从本地文件系统读取文件时出现iOS错误代码=256

  •  0
  • kregtopoli  · 技术社区  · 11 月前

    尝试打开并读取文件时出现问题。我给出错误:“代码=256无法打开文件test.csv”

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let docURL = URL(string: documentsDirectory)!
    let dataPath = docURL.appendingPathComponent("myDir/\(fileName)")
    do {
        let content = try String(contentsOf: dataPath, encoding: .utf8)
        print(content)         
    } catch {
        print(error)
    }
    

    我不确定我是否正确,如上所述保存文件是可以的。当然,当我在终端中检查路径时,一切都很好。文件存在。

    1 回复  |  直到 11 月前
        1
  •  2
  •   Bram    11 月前

    这很可能是一个无效的URL。状态代码表示 NSFileReadUnknownError ,这根本没有用。您可能可以通过使用不同的URL初始化器来修复它。

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let docURL = URL(fileURLWithPath: documentsDirectory) // <-- This line
    let dataPath = docURL.appendingPathComponent("myDir").appendingPathComponent(fileName)
    
    do {
        let content = try String(contentsOf: dataPath, encoding: .utf8)
        print(content)
    } catch {
        print("Failed to read file: \(error.localizedDescription)")
    }