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.
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 .
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.
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.
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")
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With