![](/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.