简体   繁体   中英

Swift3 not writing to the file

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.

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"}
}

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)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM