Save custom object to userdefaults iOS swift

Problem: 

I want to save my custom object into the userdefaults.I tried to save directly it throws exception

Solution:

 func getProfileData() -> MyModel {

        if let value = self.userDefaults.object(forKey: "profilemodel") as? Data{

            do {

                let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: value)

                let json = try JSONSerialization.data(withJSONObject: decodedTeams)

                let decoder = JSONDecoder()

                decoder.keyDecodingStrategy = .convertFromSnakeCase

                let decodedProfile = try decoder.decode(MyModel.self, from: json)

                return decodedProfile

            } catch {

                print(error)

            }


        }

        return MyProfileModel()

    }

    

    func setProfileData(value: MyModel) {

        do {

            let encodedResponse = (try? JSONSerialization.jsonObject(with: JSONEncoder().encode(value)))

            let data = try NSKeyedArchiver.archivedData(withRootObject: encodedResponse, requiringSecureCoding: false)

            self.userDefaults.set(data, forKey: "profilemodel")

            self.saveValue()


        } catch {

            NSLog("Unable to archive  \(error)")

        }


    }

Comments

Popular posts from this blog

Invalid bundle error while upload the app to the app Store

Saved Image in document directory and save path in coredata not able to fetch the image file iOS swift