在下面的代码中,我试图写入我在xcode项目中的文件。但对于某些问题,它没有写入它。我的文件中没有更新的文本。(JSON文件)
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"}
}
我能够通过以下方式阅读该文件:
if let path = Bundle.main.path(forResource: "mapsdatademo", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)}
注意:我正在尝试获取json数据并将其写入文件。
答案 0 :(得分:1)
iOS是沙盒。您可以从包中读取但不能写入包。写入文档目录。
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"}
}
答案 1 :(得分:-2)
你的问题是responseString.write(toFile :)
responseString = "Some Text"
do {
try self. responseString.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}catch{
print(error)
}