Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iOS Error Code=256 in try read file from local filesystem

I have a problem when trying to open the file and read it. Im giving Error: "Code=256 cannot open file 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)
}

I’m not sure if I’m doing it correctly, saving the file as above is ok. Of course when I check the path in the terminal it is fine. File exist.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It is very likely an invalid URL. The status code indicates NSFileReadUnknownError, which is not at all useful. You can probably fix it by using a different URL initializer.

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)")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading