0

I have a local json file, to read what I do as follows:

enter image description here

func readJson() {
     if let path = Bundle.main.path(forResource: "text", ofType: "json") {
            do {

                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)
                let decoder = JSONDecoder()
                let model = try decoder.decode(Textos.self, from: data)
                print("model", model)
            } catch {
                print("error file")
            }
        } else {
            print("error")
        }
    }

the read function works fine but when I want to update the file it doesn't update.

func saveJson(response: Textos) {
        do {
            let jsonEncoder = JSONEncoder()
            let jsonData = try jsonEncoder.encode(response)            //all fine with jsonData here
            let json = String(data: jsonData, encoding: String.Encoding.utf8)
            let data = Data(json!.utf8)
            if let path = Bundle.main.path(forResource: "text", ofType: "json") {
                do {
                    try? data.write(to: URL(fileURLWithPath: path)) **//not Working**
                    readJson()
                }
            }
        } catch {
            print(error)
        }

    }

the saveJson function works fine in a simulator but when I test it with a device it doesn't work.

  • When you say it doesn't work. what actually happens? Any Errors? Crashes? – chirag90 Jan 17 '20 at 13:59
  • You can't write to the device bundle, use the Documents directory instead. – James P Jan 17 '20 at 14:00
  • If you didn't mask the actual error using `try?`, you would see the error being thrown. Delete the inner `do` block, since it's useless and change `try?` to `try`, then you'll see the actual error being thrown in your `catch` block. Also, files in your `Bundle` are read-only, you need to copy the file to a writeable location first, before you could overwrite it. – Dávid Pásztor Jan 17 '20 at 14:00
  • @chirag90 no error, the file is not written, when I am going to read the file again it does not have the new thing it adds – José Luis Tovar J Jan 17 '20 at 14:03
  • You **can't** write to the bundle, it's read only. – Joakim Danielson Jan 17 '20 at 14:05
  • @JamesP If I use the Documents directory, I cannot read the json file that the application has, I know that a new one is created. (View image) – José Luis Tovar J Jan 17 '20 at 14:07
  • Sure u can. U need to add more logic to do that. If the file isn't in the documents folder, then load if from the bundle as fall back. (That is what you need to do with clean install case anyway) – Helge Becker Jan 17 '20 at 14:16
  • @JoséLuisTovarJ Did you solve your problem? I am facing this problem right now. I use 3rd party lib which is EasyStash. I am saving local json file to app sandbox directory. I am not updating this file with my textField text data. – Emre Değirmenci Apr 28 '20 at 16:05

1 Answers1

0

Short answer:

You will never be able to save.

let path = Bundle.main.path(forResource: "text", ofType: "json")

The file is within the application bundle. Access is read only.

Saving would be possible to either the document or cache folder.

let documentPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

(Example how to request the path to the user document folder. This folder is per application sandbox.

Helge Becker
  • 3,219
  • 1
  • 20
  • 33