0
func writeToFile(content: String, fileName: String) {

    let contentToAppend = content+"\n"
    let filePath = NSHomeDirectory() + "/Documents/" + fileName

    //Check if file exists
    if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
        //Append to file
        fileHandle.seekToEndOfFile()
        fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    else {
        //Create new file
        do {
            try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
        } catch {
            print("Error creating \(filePath)")
        }
    }
}

I have that code which allows me to call this function and it writes to a file. Now im stuck as to how can I read this File. I'd like to have this display the files contents inside a multi line Text box. Can someone help me with a Read function for this code?

John Martin
  • 443
  • 1
  • 4
  • 7
  • https://stackoverflow.com/questions/24097826/read-and-write-a-string-from-text-file – Abdelahad Darwish May 06 '18 at 05:48
  • 1
    Consider that `NSHomeDirectory() + "/Documents/"` does not work if the app is sandboxed. There are convenience methods in `FileManager` to get the standard directories. – vadian May 06 '18 at 06:40
  • @vadian The answers in the duplicate show the proper way to get the Documents folder. – rmaddy May 06 '18 at 06:43

0 Answers0