Search code examples
iosswiftnsuserdefaultsswift4

How to save json data on userdefaults in swift 4


enter image description here

This is my model class

class UserRoot : Mappable {
    var success : Bool!
    var user : UserDetails!
    var error = ""

    required init?(map: Map) {

    }
    func mapping(map: Map) {
        success <- map["success"]
        user <- map["user"]
        error <- map["error"]

    }
}

after successfully login i want to save this data on user defaults so that when a user have to not give login credential again. Here is my code

class Default : NSObject{
    static func saveToSharedPrefs(user: UserDetails!) {
        let d = UserDefaults.standard
        if user != nil {
            d.set(Mapper().toJSONString(user, prettyPrint: false) , forKey: "USERDETAILS")
        } else {
            d.set(nil, forKey: "USERDETAILS")
        }
        d.synchronize()
    }
}

Solution

  • Make sure your model class is inherited from NSObject class otherwise it will crash at run time.

    To store data:

    let data = NSKeyedArchiver.archivedData(withRootObject: <Your model class>)
    UserDefaults.standard.set(data, forKey: "userDetails")
    

    To retrive and convert data back

    if let data = UserDefaults.standard.value(forKey: "userDetails") as? Data {
        if let dict = NSKeyedUnarchiver.unarchiveObject(with: data) as? <Your model class> {
               print(dict)
         }
    }