Hi, I am new to fast programming, so please bear with me if I make obvious mistakes. I am trying to write data entered by a user through a text box to a text file. I can successfully do this with the code I wrote below. However, when I tried to save more data, it will replace the existing data in the text file with the new data that is being saved. for example, if I save the line “Hello world” and then save another line with the words “bye”. I will only see the string “bye” in the text file. Is there a way I can change my code so that I can see “hello world” on one line of textile and “bye” on another.
@IBAction func btnclicked(_ sender: Any) {
self.savedata(value: answer.text!)
}
func savedata (value: String){
let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
let writeString = NSString(string: answer.text!)
do {
try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8.rawValue)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
}
Any help is greatly appreciated. Thank you.