0
var file = ""
var text = ""
var path: URL?

override viewDidLoad(){

  super.viewDidLoad()


    file = "test2.csv" //this is the file I will write to 
    if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

        path = dir.appendingPathComponent(file)

        do {
            text = "Hello"
            try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
        }
        catch {/* error handling here */}

    }

   getInsightResult()
}

This piece of code is writing "Hello" to "test2.csv" perfectly in my viewDidLoad() method. However, when I run that excerpt of code in a separate method called getInsightResult(), which I call in viewDidLoad, the text that is being written is blank. However, when I print out the text it is not empty, but displays the correct text.

 func getInsightResult() {

      for x in 0...4{
          for y in 0...4{
                if(y != 3){
                      do{

                       let temp = arrayOfDataArrays[y]
                       text = String(temp[x])
                       print("Tester:\(temp[x])")
                       print("Text:" + text)

                       try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
                        }
                       catch {/* error handling here */}
                            }

                          }
                       text = "\n"
                       do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
                       catch {/* error handling here */}

                    }

       }
Eric Agredo
  • 487
  • 1
  • 4
  • 13
  • See http://stackoverflow.com/questions/27327067/append-text-or-data-to-text-file-in-swift for info on appending text to a file. – rmaddy Feb 24 '17 at 04:22

2 Answers2

3

The issue is merely a misconception on your part: you seem to imagine that String's write method appends to an existing file, and it doesn't. It replaces the contents of the file.

Your code is thus working perfectly. The text is being written to the file, every time you say text.write.... The "problem" is that this line:

text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}

...replaces everything in the file with a single linefeed. And since that is the last line executed, that is the state of the file when we finish.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Is there a way to append to an existing file? That is what I am trying to do, ultimately – Eric Agredo Feb 24 '17 at 04:07
  • Sure, just search on "iOS text file append" or similar. – matt Feb 24 '17 at 04:58
  • Or accumulate everything into a string and then write that string out, once. Instead of setting `text` every time, append to `text` every time; then write `text` to a file, once, at the very end. – matt Feb 24 '17 at 09:57
  • Well, I am trying to format my CSV file in a specific way and appending to the `text` string will be complicated. – Eric Agredo Feb 24 '17 at 17:02
-1

try this

let file = "file.txt"
let text = "text content"

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    let path = dir.appendingPathComponent(file)
    do {
        try text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
    }
    catch {}
}
Chakery
  • 15
  • 3
  • Please explain what was wrong with the code in the question and explain how your answer solves the problem. – rmaddy Feb 24 '17 at 04:14