【问题标题】:How Update Local JSON file Swift ios 13 [duplicate]如何更新本地 JSON 文件 Swift ios 13 [重复]
【发布时间】:2020-05-04 10:16:15
【问题描述】:

我有一个本地 json 文件,读取我的操作如下:

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

读取功能工作正常,但是当我想更新文件时它不会更新。

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

    }

saveJson 函数在模拟器中可以正常工作,但是当我使用设备对其进行测试时,它就不起作用了。

【问题讨论】:

  • 当你说它不起作用时。实际发生了什么?任何错误?崩溃?
  • 您无法写入设备包,请改用 Documents 目录。
  • 如果您没有使用try? 掩盖实际错误,您会看到抛出的错误。删除内部的do 块,因为它没用,将try? 更改为try,然后你会看到catch 块中抛出的实际错误。此外,Bundle 中的文件是只读的,您需要先将文件复制到可写位置,然后才能覆盖它。
  • @chirag90 没有错误,文件没有写入,当我要再次读取文件时,它没有添加的新内容
  • 不能写入包,它是只读的。

标签: ios json swift


【解决方案1】:

简答:

你将永远无法保存。

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

该文件位于应用程序包中。访问是只读的。

可以保存到文档或缓存文件夹。

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

(示例如何请求用户文档文件夹的路径。此文件夹是每个应用程序沙箱。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多