1

In the below code I am trying to write to a file that I have in my project in xcode. But for some issue its not writing to it. I am getting no updated text in my file.(JSON file)

        responseString = "Some Text"           
        if let path = Bundle.main.path(forResource: "mapsdatademo", ofType: "json") {
            do{
                try responseString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8)
            }catch {"Error writting data"}
        }

I am able to read the file with:

if let path = Bundle.main.path(forResource: "mapsdatademo", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)}

Note: I am trying get get json data and write that into a file.

Subhransu Mishra
  • 3,035
  • 11
  • 40
  • 47
  • 1
    Possible duplicate of [How to save an array to .plist in the App's mainBundle in swift](http://stackoverflow.com/questions/26889507/how-to-save-an-array-to-plist-in-the-apps-mainbundle-in-swift) – rmaddy Oct 25 '16 at 04:54

2 Answers2

1

iOS is sandboxed. You can read from the bundle but not write to it. Write to the documents directory.

if var path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
    path = path.appendingPathComponent("mapsdatademo.json")
    do{
        try responseString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8)
    }catch {"Error writting data"}
}
Josh Homann
  • 15,933
  • 3
  • 30
  • 33
-2

your problem is responseString.write(toFile:)

responseString = "Some Text"
 do {
         try self. responseString.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
 }catch{
            print(error)
 }
ikbal
  • 1,114
  • 1
  • 11
  • 30