Issue
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.
Solution
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")
}
}
To read an object from a JSON file in your documents directory:
- Build A URL to the file using the
getDocumentsDirectory()
function above, along withURL.appendingPathComponent()
- Use the Data method
init(contentsOf:options:)
to create a Data object from the file's contents. - Create a
JSONDecoder
and use it to convert your data to a JSON object. (Your object will need to conform to the Codable protocol.)
Answered By - Duncan C Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.