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

to retrieve from UserDefaults

func get(_ key: String)-> JSON? {
    
    if let standard = UserDefaults.standard.data(forKey: key), let data = try? standard.toData() {
        return JSON(data)
    } else {
        return nil
    }
}

You should parse everything to Data, in order to save model (Better from JSON / JSONSerialization) to UserDefaults

Coded In Swift 5.x


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.


Swift 5+

 func saveJSON(json: JSON, key:String){
   if let jsonString = json.rawString() {
      UserDefaults.standard.setValue(jsonString, forKey: key)
   }
}

    func getJSON(_ key: String)-> JSON? {
    var p = ""
    if let result = UserDefaults.standard.string(forKey: key) {
        p = result
    }
    if p != "" {
        if let json = p.data(using: String.Encoding.utf8, allowLossyConversion: false) {
            do {
                return try JSON(data: json)
            } catch {
                return nil
            }
        } else {
            return nil
        }
    } else {
        return nil
    }
}

Use this if you using SwiftyJSON.


I used the following code and it works like a charm!

NSString *json = @"{\"person\":{\"first_name\":\"Jim\", \"last_name\":\"Bell\"}} ";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if([defaults objectForKey:@"json"]== nil){
    [defaults setObject:json forKey:@"json"];
    //[defaults synchronize];
}
else{
    NSLog(@"JSON %@", [defaults objectForKey:@"json"]);
}

First try to see whether you can save a hard-coded string to the NSUserDefaults first.

Also try to call a [defaults synchronize]; call when you want to save the data. Although that is NOT required, it might be needed in extreme conditions such as if the app is about to terminate.