Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing to text file in swift 3

I am trying to write data that is inputted by a user via UITextField to a text file. I am successfully able to do this by the code I have written below. However, when I tried to save more data it will replace the existing data in the textfile with the new data that is being saved. for example, if I save the string 'hello world' and then save another string saying 'bye'. I will only see the string 'bye' in the textfile. Is there a way I can modify my code so I can see 'hello world' on one line of the 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 {
      // Write to the file
      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)
   }
}
like image 291
Aneesa Avatar asked Feb 21 '17 11:02

Aneesa


1 Answers

Here is an example using FIleHandler, adapted to Swift 3, from here (of course you should add all the error handling code that's missing in my example) :

let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
let fileurl =  dir.appendingPathComponent("log.txt")

let string = "\(NSDate())\n"
let data = string.data(using: .utf8, allowLossyConversion: false)!

if FileManager.default.fileExists(atPath: fileurl.path) {
    if let fileHandle = try? FileHandle(forUpdating: fileurl) {
        fileHandle.seekToEndOfFile()
        fileHandle.write(data)
        fileHandle.closeFile()
    }
} else {
    try! data.write(to: fileurl, options: Data.WritingOptions.atomic)
}
like image 174
Bogdan Farca Avatar answered Nov 19 '22 20:11

Bogdan Farca