0

I want to replace the contents of a JSON file with data coming from an API call. I have tried the following:

let filePath: String = Bundle.main.path(forResource: "shared", ofType: "json")!
let fileUrl: URL = URL(fileURLWithPath: filePath)

do {
    try jsonData.write(to: fileUrl, atomically: false, encoding: .utf8)

    do {
        let newData = try String(contentsOf: fileUrl, encoding: .utf8)
        print("New Data: \(newData)")
    } catch {
        print("Failed to read updated file data")
    }
} catch {
    print("Failed to write data to file")
}

I've confirmed that "shared.json" is listed under "Copy Bundle Resources". I'm not getting any errors. Yet the contents of "shared.json" never changes. What am I doing wrong?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Darrell Brogdon
  • 6,843
  • 9
  • 47
  • 62
  • 2
    Unrelated to your issue, but you can get a `URL` to a bundled file directly with one function, `Bundle.main.url(forResource: withExtension:)`, there's no need to convert the path to a `URL` manually. – Dávid Pásztor May 17 '18 at 16:13
  • 2
    https://stackoverflow.com/a/12679524/1361672 – RLoniello May 17 '18 at 16:19

1 Answers1

2

You can't.

Files embed in your app cannot be edited. At first install, you have to copy your embedded files into the Documents directory and then edit this version.

CZ54
  • 5,488
  • 1
  • 24
  • 39