0

I'm trying to do a very simple read, write, and persist in a text file (named data.txt, and stored in the main project folder) in a basic iOS app. This is just a learning exercise.

I can read pre-existing text from data.txt just fine. When I write to the text file and read from it afterwards, the written text is there.

However, if I stop my app simulator, the written text goes away.

Is there a trick to persisting to file across app restarts?

Here is my code:

 var originalData : String = ""

//read from file
print("reading from data file")
if let path = Bundle.main.path(forResource: "data", ofType: "txt") {
  do {
    originalData = try String(contentsOfFile: path, encoding: .utf8)
    print("originalData = \(originalData)")
  }
  catch {
    print(error)
  }
}

//write to file
let newData = "\(originalData), new text"
print("writing to data file")
if let fileURL = Bundle.main.url(forResource: "data", withExtension: "txt") {
  do {
    try newData.write(to: fileURL, atomically: false, encoding: String.Encoding.utf8)
  }
  catch let error as NSError {
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
  }
}

//read from file
print("reading from data file again")
if let path = Bundle.main.path(forResource: "data", ofType: "txt") {
  do {
    let moreData = try String(contentsOfFile: path, encoding: .utf8)
    print("moreData = \(moreData)")
  }
  catch {
    print(error)
  }
}

The output printed is:

reading from data file
originalData = Line 1 of data file

writing to data file
reading from data file again
moreData = Line 1 of data file
, new text

But then when I stop my app simulator and open data.txt, the contents are just: Line 1 of data file

A B
  • 131
  • 1
  • 13

1 Answers1

1

What you're trying to do here makes no sense and is strictly forbidden:

if let fileURL = Bundle.main.url(forResource: "data", withExtension: "txt") {
  do {
    try newData.write(to: fileURL, atomically: false, encoding: String.Encoding.utf8)
  }

Your running app may not alter a file inside your app bundle! That's a gross security violation. Copy the file out to your sandboxed Documents folder and work with it there. It will then persist across relaunching the app.

matt
  • 515,959
  • 87
  • 875
  • 1,141