-3

I'm just getting the ropes to reading and writing data from an iOS app using a .json file. Currently I have an app where whatever is in a text field will be written to a json file, and then when a button is pressed it displays whatever was just written to a label. Basically just testing reading and writing. It reads the initial value from the json file fine, but when I write to the json file then try to read it again, it gives me the error:

"Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}".

Any help is appreciated.

@IBAction func UpdateLabelTapped(_ sender: UIButton) {
    let path = Bundle.main.path(forResource: "SaveData", ofType: "json")
    let url = URL(fileURLWithPath: path!)

    let data = try! Data(contentsOf: url)
    let obj = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)

    if let str = (obj as! NSDictionary).value(forKey: "message") {
        self.DataLabel.text = str as? String ?? ""
    }
}

@IBAction func WriteToJSONTapped(_ sender: UIButton) {
    let path = Bundle.main.path(forResource: "SaveData", ofType: "json")
    let url = URL(fileURLWithPath: path!)

    let dict = NSMutableDictionary()
    dict.setValue("Writing JSON!!", forKey: "message")
    dict.write(to: url, atomically: true)
}

It occurs on the line that says let obj = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)

Gleb A.
  • 1,180
  • 15
  • 24
Mrosky
  • 13
  • 4
  • What exactly do you want to do? Write json on tap of a button and read it back on tap of the other button? – HAK May 30 '18 at 19:35
  • Exactly. When one button is pressed it writes a value to a JSON file, and when the other button is pressed it reads and displays it – Mrosky May 30 '18 at 19:37
  • 2
    The error says that the first character is not valid JSON. Apart from the issue you cannot write into the application bundle. The bundle is read-only. And don't use `NS(Mutable)Dictionary` in Swift, use native types. By the way the `write` API of `NSDictionary` writes property list, not JSON. And `value(forKey` is bad and uppercased variable and function names is bad, too. – vadian May 30 '18 at 19:48
  • For reading and writing a file see: https://stackoverflow.com/questions/24097826/read-and-write-a-string-from-text-file – HAK May 30 '18 at 19:59

1 Answers1

1

This looks suspicious to me:

dict.write(to: url, atomically: true)

write(to:atomically:) saves the dictionary in property list format, not JSON. To write JSON try the following:

let jsonData = try! JSONSerialization.data(withJSONObject: dict)
try! jsonData.write(to: url, options: [])

Note: make sure you handle errors properly in production code. :-)

Gleb A.
  • 1,180
  • 15
  • 24