Matt Kelly
Matt Kelly

Reputation: 1491

Swift 2.0 - Unable to Write to Text File (OS X)

I have a text file that I will be reading and writing to. I have gotten the code to read successfully, but am unable to write to the text file again. I want to overwrite everything (not amend).

    if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
        let path = dir.stringByAppendingPathComponent("airports.txt")

        var strTextToWrite:String = String()        
        strTextToWrite = "Test"

        do {
            try strTextToWrite.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
        }
        catch { print("Error") }

    }

The above code doesn't throw an error (i.e. the word 'Error' isn't printed as per my catch code), but the text file remains unedited, retaining the value it had before the code was run.

The text file is contained inside the X-Code project as shown below:

Text File Location

I'm at a real loss here, I don't understand why the code isn't working. I have confirmed that it is being run (by printing the value of strTextToWrite before and after the do statement, and it is definitely running through the do block of code because it isn't being caught by the catch block. The only thing I can think of is that the code is pointing at the wrong file (but the file name is correct, as you can verify with the screenshot above).

What am I doing wrong? Thanks in advance.

Upvotes: 1

Views: 179

Answers (1)

Code Different
Code Different

Reputation: 93141

You are looking at 2 different files: the one you write to is ~/Documents/airport.txt while the one you see (and check) in Xcode is located in your project folder. To see the update, you need to reference the file in Xcode, not make a copy of it.

  1. Right click airport.txt in your Project Navigator and click Delete > Move to Trash
  2. Go to ~/Documents/airport.csv and drag it into your Xcode project. Do not add it to any target and unselect "Copy Items if Necessary"

You now have created a link to the file.

enter image description here

Modifying files in your bundle is generally a bad idea. If you need a place to output a temporary file, use the app's subfolder under ~/Application Support or the system's temp folder.

Upvotes: 1

Related Questions