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.
CodePudding user response:
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")
}
}