1

I'm using this code to save a string to an xml file in my project

let saveTo = statisticsI.toXMLString()
let filepath = Bundle.main.url(forResource: "statistics", withExtension: "xml")
let filepathAlt = Bundle.main.path(forResource: "statistics", ofType: "xml")
print(filepathAlt!)
do {
    try saveTo.write(to: filepath!, atomically: false, encoding: String.Encoding.utf8)
    let contents = try String(contentsOfFile: filepathAlt!)
    print("FILE CONTENTS \(contents)")
}
catch let error as NSError {
    print("Error writing values \(error)")
}

Printing the file contents returns the xml correctly, but when I stop running the application, the file hasn't been updated

When the above code is run, the file has already been read by a seperate function. Is the fact that the file has already been accessed (and its path still stored in a variable) the issue?

pacification
  • 5,838
  • 4
  • 29
  • 51
Big Jeff
  • 19
  • 3
  • You don't write in Bundle.main. You have to write else where. See there: https://stackoverflow.com/a/24098149/1801544 with `FileManager()` for instance to get a path where you can write. – Larme Sep 06 '18 at 13:00

1 Answers1

1

when I stop running the application, the file hasn't been updated

You can't write into the application bundle in iOS. Try using a path into the Documents folder or some other place within the app's sandbox.

Caleb
  • 124,013
  • 19
  • 183
  • 272