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

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

Posted by: admin February 24, 2018 Leave a comment

Questions:

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
}
Answers:

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.

Questions:
Answers:

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.

Questions:
Answers:

Here’s a swift example that works

import SwiftyJSON
class Users{

    init(){
        let yourJSON = {"name":"Deeznuts"}
        let response = JSON(yourJSON)

        // Store your 
        let httpMessage = response["name"].stringValue 

    }
}

Questions:
Answers:

swift 3

 func setObject(value:JSON ,key:String){
        let pref = UserDefaults.standard
        pref.set(value.rawString(), forKey: key)
        pref.synchronize()
 }

func getObject(key:String) -> JSON{
    let pref = UserDefaults.standard
    let string = pref.value(forKey: key) as! String
    let dataFromString = string.data(using: String.Encoding.utf8, allowLossyConversion: false)
    return JSON(data: dataFromString!)
}