2

I am working on a project in swift where I need to write data to a JSON file, print that data, and be able to add more data as it arrives. At the moment, I can write to the JSON and display the first inputted data but after I add more and attempt to display it again, it just prints the new data.

I am using textView to display the data and using textFields and textView to get the data.

The code below should give you a better understanding.


 @IBAction func addWords(_ sender: UIButton) {
        let data: [String:String] = [
            "Name": nameField.text ?? "N/A",
            "Definition": defView.text ?? "N/A",
            "Part of Speech": posField.text ?? "N/A"
        ]
        let fileUrl = Bundle.main.url(forResource: "data", withExtension: "json")!
        if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: []) {
            try! jsonData.write(to: fileUrl)
            nameField.text = ""
            defView.text = ""
            posField.text = ""
        } else {
            print("Failed to save")
        }
    }

    @IBAction func loadData(_ sender: UIButton) {
        let fileUrl = Bundle.main.url(forResource: "data", withExtension: "json")!
        let responseData: Data? = try! Data(contentsOf: fileUrl)
        if let responseData = responseData {
            let json: Any? = try? JSONSerialization.jsonObject(with: responseData, options: [])
            if let json = json {
                let dictionary: [String: Any]? = json as? [String: Any]
                if let dictionary = dictionary {
                    for names in dictionary {
                        let name: String = dictionary["Name"] as! String
                        let definition: String = dictionary["Definition"] as! String
                        let pos: String = dictionary["Part of Speech"] as! String
                        print(name)
                        textView.text = ("Name: \(name) (\(pos))\n Definition: \(definition)\n ")
                    }
                }
            }
        }
    }
'''
sandpat
  • 1,478
  • 12
  • 30
Vshastra
  • 63
  • 7
  • *At the moment I can write to the JSON*. Actually you can't. The files in the application bundle are read only. If you want to modify files save them in the Documents folder. – vadian Jan 21 '20 at 19:04
  • @vadian if thats the case, how would I go about saving them to the Documents folder? – Vshastra Jan 21 '20 at 19:13
  • 2
    Please see https://stackoverflow.com/questions/24055146/how-to-find-nsdocumentdirectory-in-swift – vadian Jan 21 '20 at 19:17

0 Answers0