PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

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

 July 23, 2022     ios, json, swift, xcode     No comments   

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 with URL.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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing