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()
}
}
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
Using ObjectMapper pod.
To store data:
To retrive and convert data back
You can use Data to store this json in the user defaults like this:
you can not store mapper in NSUserDefault, you can only store NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary.
NSKeyedArchiver
converts your mapper intoNSData
which you can store intouserdefault
.