Reputation: 134
This is the set function
func setSelectedDivisions(_ division:[Division]) {
if (division.count != 0) {
self.userDefaults.set(division.toJSONString(), forKey: "selectedDivisions")
self.userDefaults.synchronize()
}
else{
self.userDefaults.removeObject(forKey: "selectedDivisions")
self.userDefaults.synchronize()
}
}
and this is the get function
func getSelectedDivisions() -> [Division] {
if let json = self.userDefaults.value(forKey: "selectedDivisions"){
print(json)
}
if let json = self.userDefaults.value(forKey: "selectedDivisions") as? Array<Dictionary<String, Any>> {
if json.count != 0{
let divisions = Mapper<Division>().mapArray(JSONArray: json)
if divisions.count != 0{
return divisions
}
}
}
return []
}
in get function i got error told me that my serialization is wrong. this is the json i trying to get it
[{"name":"أ","img":"http://www.smsalmaali.com/images/cclass/21.jpg","name2":"الصف الاول","id1":"21","id2":"1"}]
any idea to fix it ?
Upvotes: 0
Views: 2286
Reputation: 4523
Using SwiftyJSON is really simple
Xcode 8+, Swift 3x
func saveJSON(json: JSON) {
UserDefaults.standard.setValue(j.rawString()!, forKey: "YOUR_KEY")
}
func getJSON() -> JSON {
return JSON.parse(UserDefaults.standard.value(forKey: "YOUR_KEY") as! String)
}
Upvotes: 0
Reputation: 1067
i think this line of code is wrong
if let json = self.userDefaults.value(forKey: "selectedDivisions") as? Array<Dictionary<String, Any>>
first you need to convert json string into array object , like follows
let data = (self.userDefaults.value(forKey: "selectedDivisions") as! String).data(using: String.Encoding.utf8) as NSData?
if data == nil || data!.length == 0 {
return
} else {
do {
let resultJSON = try JSONSerialization.jsonObject(with: data! as Data, options: .mutableContainers)
if let json = resultJSON as? Array<Dictionary<String, Any>> {
// do something
}
} catch _ {
print("exception ")
}
Upvotes: 1