简体   繁体   中英

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. I've seen only tutorial for string or image, but if I want to save a json I don't know how.

The typical way to create JSON data is to use a JSONEncoder:

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

let data = try encoder.encode(yourJsonObject)

That gives you a Data object in the variable data . As others have said, saving a Data object to documents is quite easy. 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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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