Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving swifty json array to user defaults

i have a json data which gives the following information:

let data = [
  {
    "QuestionTitle" : "Entomology is the science that studies",
    "Id" : 205,
    "Options" : [
      { "Option" : "Insects", "Id" : 810 },
      { "Option" : "The origin and history of technical and scientific terms", "Id" : 811 },
      { "Option" : "The formation of rocks", "Id" : 812 },
      { "Option" : "Behavior of human beings", "Id" : 809 }
    ]
  },
  {
    "QuestionTitle" : "A train running at the speed of 60 km\/hr crosses a pole in 9 seconds. What is the length of the train?",
    "Id" : 199,
    "Options" : [
      { "Option" : "120 metres", "Id" : 785 },
      { "Option" : "324 metres", "Id" : 787 },
      { "Option" : "180 metres", "Id" : 786 },
      { "Option" : "150 metres", "Id" : 788 }
    ]
  }
]

I am using swiftyjson. I want to save the entire array using nsuserdefaults.

GlobalVar.defaults.set(json, forKey: "questionArray")
GlobalVar.defaults.synchronize()

However, I get an error

"[User Defaults] Attempt to set a non-property-list object".

Please assist i am new to swift. I have also checked other similar questions but seems to not work.

like image 866
Dyana Avatar asked Aug 02 '17 09:08

Dyana


People also ask

How do I save a JSON response in Swift?

Save JSON string to file Saving a JSON string will be the same as saving any other kind of string. Since Swift will see it as a String object, we can use the write(to:) method that is built into String .

What is user defaults for Swift?

UserDefaults lets you store key-value pairs, where a key is always a String and value can be one of the following data types: Data, String, Number, Date, Array or Dictionary. This tutorial will show you how to use UserDefaults in Swift. UserDefaults saves its data in a local plists file on disk.

How do I use Swifty JSON?

To use SwiftyJSON, you need to convert your JSON string into a Data object, then send it in for parsing. Once that's done, you simply request data in the format you want, and (here's the awesome bit) SwiftyJSON is guaranteed to return something.


2 Answers

You cannot save SwiftyJSON's custom type JSON to UserDefaults but you can save the raw array because a deserialized JSON collection type is property list compliant.

Just call arrayObject on the JSON object:

GlobalVar.defaults.set(json.arrayObject, forKey: "questionArray")
like image 139
vadian Avatar answered Sep 24 '22 14:09

vadian


Swift 3.0

You can save SwiftyJSON custom type data as like below.

guard let rawData = try? json.rawData() else { return }
UserDefaults.standard.setValue(rawData, forKey: "Your_key")

And, To retrieve JSON data from UserDefaults, you can do like this way.

guard let data = UserDefaults.standard.value(forKey: "Your_key") as? Data else { return }

let json = JSON(data) 
like image 41
Jaydeep Vora Avatar answered Sep 23 '22 14:09

Jaydeep Vora