0

I have a local .json file and I want to read and write data to it. With reading, I have no problems:

let file = Bundle.main.url(forResource: "categories", withExtension: "json")
let data = try? Data(contentsOf: file)
let json = try? JSONSerialization.jsonObject(with: data, options: [])

But writing doesn't work. My code(jsonData & file not nil):

let dict = ["data": categories.compactMap { $0.dictionary }]
let file = Bundle.main.url(forResource: "categories", withExtension: "json")
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
try? jsonData?.write(to: file!)

.json file inside looks like this:

{
    "data" : [
        {
            "id" : "new",
            "name" : "New"
        }]
}
Tabula Rasa
  • 183
  • 10

1 Answers1

1

You cannot edit an embedded file. You have to first copy it from Bundle to Documents directory and then work ( edit ) on this file

CZ54
  • 5,488
  • 1
  • 24
  • 39