How can I save and then load a JSON in NSUserDefaults with SwiftyJSON?

Michele Bontorno picture Michele Bontorno · Mar 3, 2016 · Viewed 13.5k times · Source

in my iOS project I need to save an entire JSON as user data and then reload it on next app launch. Squashing it into many values and then recreate the JSON is not an option, I just need some serializable way of saving the entire raw JSON. I tried to convert it to String by doing json.rawString() and recreate it by passing the obtained string to JSON(string), but it doesn't work.

I'm both astonished by the difficulty of making such a simple thing and by the lack of informations about a thing like this online, so I can not wait to discover how to do that :)

Example:

public func saveJSON(j: JSON) {
    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setValue(j.rawString()!, forKey: "json")
    // here I save my JSON as a string
}

public func loadJSON() -> JSON {
    let defaults = NSUserDefaults.standardUserDefaults()
    return JSON(defaults.valueForKey("json") as! String))
    // here the returned value doesn't contain a valid JSON
}

Answer

Michele Bontorno picture Michele Bontorno · Mar 5, 2016

Thank you for your answers but they didn't solve my problem. I finally found the solution, which was really simple in facts:

public func loadJSON() -> JSON {
    let defaults = NSUserDefaults.standardUserDefaults()
    return JSON.parse(defaults.valueForKey("json") as! String))
    // JSON from string must be initialized using .parse()
}

Really simple but not documented well.