0

I have decoded my Json to structure and now I have array of objects that each objects has some values so I want when user select item in collection View the selected object in array append to the array of objects in UserDefaults I read similar questions so I used this Function Below But it won't work

@objc func likeOrDislike (_ sender : UIButton!) {
    let arrays = UserDefaults.standard.value(forKey: "Liked") as? [ListsModel.ResultValue]
    print(arrays as Any)
    var items = arrays
    let item = self.adv.resultValue[sender.tag]
    if arrays != nil {
        if items!.contains(where: {($0.id == item.id)}) {
            items!.filter({($0.id == item.id)})
        } else {
            items!.append(item)
        }
    } else {
       items = [item]
    }
    UserDefaults.standard.setValue(items, forKey: "Liked")
    UserDefaults.standard.synchronize()
}

and here is the model that I use for decode

public class ListsModel {
  struct Response : Decodable {
    var resultValue : [ResultValue]
  }

  struct ResultValue : Decodable {
    let id : String?
    let title : String?
    let user_id : String?
    let username : String?
    let user_image : String?
    let release_date : String?
    let start_date : String?
    let salary : String?
    let salary_id : String?
    let work_field_id : String?
    let adv_type_id : String?
    let work_field : String?
    let description : String?
    let adv_base_id : String?
    let is_spec : String?
    let status : String?
    let p_expire_date : String?
  }
}
DilbertFan
  • 113
  • 1
  • 1
  • 9
Saeed Rahmatolahi
  • 1,317
  • 2
  • 27
  • 60

1 Answers1

1

Convert all the model object to string by stringify and then store to user deafaults and use where you want to use.

Anil Kumar
  • 1,830
  • 15
  • 24
  • yes this is some way But I want to store all of them – Saeed Rahmatolahi Mar 16 '19 at 10:11
  • 1
    You can add all of them you need to strifgy the object or array of object that you get from the model . 1st you create model then store data into model after completion convert all the model data to stringfy and store into your userdefault – Anil Kumar Mar 16 '19 at 10:21
  • No, you shouldn't save custom model to `UserDefaults`. You should use `FileManager` or database for it – Robert Dresler Mar 16 '19 at 11:09
  • See like this i use object mapper for custom model class then convert into jsonstring and store into userdefault . //1. custom model if let userInfo = Mapper().map(JSONObject: dictionary["login"] ){ if let JSONString = Mapper().toJSONString(userInfo, prettyPrint: true) { //2 User Info:- let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: JSONString) UserDefaults.standard.set(encodedData, forKey: "userinfo") } } – Anil Kumar Mar 16 '19 at 18:26