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 still no idea of how to fix the problem. How do I specify the correct location and file?
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(.documentationDirectory,.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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments