Writing to a text file in swift 3

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 {
      // 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)
   }
}

Any help is greatly appreciated. Thank you.

+6
2

, FIleHandler, Swift 3, (, , ):

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)
}
+7

Swift 4 String.

extension String {

func writeToFile(fileName: String) {
    guard let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
        return
    }

    let fileUrl = dir.appendingPathComponent(fileName)
    guard let data = self.data(using: .utf8) else {
        return
    }

    guard FileManager.default.fileExists(atPath: fileUrl.path) else {
        try? data.write(to: fileUrl, options: .atomic)
        return
    }

    if let fileHandle = try? FileHandle(forUpdating: fileUrl) {
        fileHandle.seekToEndOfFile()
        fileHandle.write(data)
        fileHandle.closeFile()
    }
}

}

-1

Source: https://habr.com/ru/post/1670403/


All Articles