【发布时间】:2020-05-04 10:16:15
【问题描述】:
我有一个本地 json 文件,读取我的操作如下:
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 没有错误,文件没有写入,当我要再次读取文件时,它没有添加的新内容
-
你不能写入包,它是只读的。