![](/img/trans.png)
[英]How to download a file and save it to the documents directory with AFNetworking?
[英]How to save a json file in documents directory?
我想将我的 json 文件保存在文档目录中并从 iOS 的文档目录中读取它。 我只看过字符串或图像的教程,但如果我想保存一个 json,我不知道如何。
创建 JSON 数据的典型方法是使用 JSONEncoder:
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(yourJsonObject)
这为您提供了变量data
中的Data
对象。 正如其他人所说,将Data
对象保存到文档中非常容易。 代码看起来像这样(下面的内容仅供参考,可能包含轻微的语法错误。)
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func saveDataToDocuments(_ data: Data, jsonFilename: String = "myJson.JSON") {
let jsonFileURL = getDocumentsDirectory().appendingPathComponent(jsonFilename)
do {
try data.write(to: jsonFileURL)
} catch {
print("Error = \(error.description")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.