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)