Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
}
like image 304
Michele Bontorno Avatar asked Mar 03 '16 17:03

Michele Bontorno


People also ask

How do I save an array of objects in Swift?

You'll need to convert the object to and from an NSData instance using NSKeyedArchiver and NSKeyedUnarchiver . For example: func savePlaces(){ let placesArray = [Place(lat: 123, lng: 123, name: "hi")] let placesData = NSKeyedArchiver. archivedDataWithRootObject(placesArray) NSUserDefaults.

What is SwiftyJSON in Swift?

Swift version: 5.6. SwiftyJSON is a super-simplified JSON parsing library that gives you clearer syntax than the built-in iOS libraries (yes, even more than JSONEncoder from Codable ), and is free. You can download it from here – unzip the file you downloaded, then look in its Source directory and drag SwiftyJSON.


2 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.

like image 79
Michele Bontorno Avatar answered Sep 28 '22 09:09

Michele Bontorno


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.

like image 42
Ahmadreza Avatar answered Sep 28 '22 11:09

Ahmadreza