Search code examples
iosswiftfile

How to write to a file at a specific directory in the project?


I'm trying to output some strings I've gathered in my app to a text file.

The text files will always exist in my project, like so:

I'm trying to overwrite whatever is in the file with a new (multi-lined) string:

func writeFile(){
    let theFile: FileHandle? = FileHandle(forWritingAtPath: "./MyFiles/file.txt")
    
    if theFile != nil { // This is always nil!!!
        let data = ("Some text\nline 2\nline3\n" as String).data(using: String.Encoding.utf8)
        
        // Write it to the file
        theFile?.write(data!)
        
        // Close the file
        theFile?.closeFile()
    } else {
        print("Writing failed.")
    }
} // End file writing

However, the FileHandler always returns nil. I suspect that this is because I'm supplying the path and/or filename incorrectly?

I've been googling and stack overflowing for a couple of hours now and I still have no idea of how to fix the problem. How do I specify the correct location and file?


Solution

  • You cannot write file outside of the application sandbox. Each iOS app have individual directories Document, Library, tmp to store data.

    func writeFile(){
        
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentsDirectory,.userDomainMask,true)
        let theFile: FileHandle? = FileHandle(forWritingAtPath: "\(documentsPath)/MyFiles/file.txt")
        
        if theFile != nil { // This is always nil!!!
            let data = ("Some text\nline 2\nline3\n" as String).data(using: String.Encoding.utf8)
            
            // Write it to the file
            theFile?.write(data!)
            
            // Close the file
            theFile?.closeFile()
        }
        else {
            print("Writing failed.")
        }
        
    } // End file writing