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()
}
}
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)
}
}
In swift 4 Better use JSONEncoder to encode your Swift object to JSON and JSONDecoder to decode your JSON to Swift object, Confirm Codable protocol to your Model class before encode and decode. You can follow this answer from stack overflow
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