简体   繁体   English

如何将 json 文件保存在文档目录中?

[英]How to save a json file in documents directory?

I want to save my json file in document directory and read it from document directory in iOS.我想将我的 json 文件保存在文档目录中并从 iOS 的文档目录中读取它。 I've seen only tutorial for string or image, but if I want to save a json I don't know how.我只看过字符串或图像的教程,但如果我想保存一个 json,我不知道如何。

The typical way to create JSON data is to use a JSONEncoder:创建 JSON 数据的典型方法是使用 JSONEncoder:

let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted

let data = try encoder.encode(yourJsonObject)

That gives you a Data object in the variable data .这为您提供了变量data中的Data对象。 As others have said, saving a Data object to documents is quite easy.正如其他人所说,将Data对象保存到文档中非常容易。 The code would look something like this (the below is intended as a guide and may contain minor syntax errors.)代码看起来像这样(下面的内容仅供参考,可能包含轻微的语法错误。)

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.

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