1

I have a JSON file witch copied locally into xcode which I can read it through the main bundle. But then I have problem update this JSON file because everytime i write into a new JSON file create in app document folder.

Here are the sample JSON file

[
{
    "id": "5c8a80f52dfee238898d64cf",
    "firstName": "Phoebe",
    "lastName": "Monroe",
    "email": "phoebemonroe@furnafix.com",
    "phone": "(903) 553-3410"
},
{
    "id": "5c8a80f575270ddb54a18f86",
    "firstName": "Lidia",
    "lastName": "Wilkins",
    "email": "lidiawilkins@furnafix.com",
    "phone": "(997) 482-3866"
}
]

Here are the code which I update the JSON file

  let mainUrl = Bundle.main.url(forResource: "data", withExtension: ".json")!

    let json = JSON(contact)
    let hello = json.arrayObject
    let str = hello?.description
    let data = str!.data(using: String.Encoding.utf8)!
    do{
    try data.write(to: mainUrl, options: [])
        } catch {
                print(error)
}
}
kiki
  • 41
  • 1
  • 10
  • Possible duplicate of [How to access file included in app bundle in Swift?](https://stackoverflow.com/questions/37580015/how-to-access-file-included-in-app-bundle-in-swift) – Joakim Danielson Sep 29 '19 at 11:41

1 Answers1

1

You can't save the file in main bundle again as it's read-only , you need to copy it to say documents/library folder where you can read/write


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let from = Bundle.main.url(forResource: "data", withExtension: "json")!

        let to = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("result.json")

        do {

            try FileManager.default.copyItem(at: from, to: to)

            print(try FileManager.default.contents(atPath: to.path))

            let wer = Data("rerree".utf8 )

            try wer.write(to: to)

            print(try FileManager.default.contents(atPath: to.path))

        }
        catch {

            print(error)
        }

    }

}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87