如何在swift 4中保存用户默认的json数据

时间:2018-03-29 12:01:29

标签: ios swift nsuserdefaults swift4

enter image description here

这是我的模特课

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"]

    }
}

成功登录后,我想将此数据保存在用户默认值上,以便用户不必再次提供登录凭据。这是我的代码

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()
    }
}

4 个答案:

答案 0 :(得分:1)

您可以使用Data将此json存储在用户默认值中,如下所示:

let myData = NSKeyedArchiver.archivedData(withRootObject: myJson)
UserDefaults.standard.set(myData, forKey: "userJson")

let recovedUserJsonData = UserDefaults.standard.object(forKey: "userJson")
let recovedUserJson = NSKeyedUnarchiver.unarchiveObject(with: recovedUserJsonData)
  

编辑

您无法在NSUserDefault中存储映射器,只能存储 NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary

NSKeyedArchiver将您的映射器转换为NSData,您可以将其存储到userdefault

答案 1 :(得分:1)

  

确保您的模型类继承自NSObject类,否则它将在运行时崩溃。

存储数据:

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

要追溯并转换数据

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

答案 2 :(得分:1)

在swift 4中更好地使用 JSONEncoder 将Swift对象编码为JSON,将 JSONDecoder 编码为将JSON解码为Swift对象,确认 Codable 协议在编码和解码之前到您的Model类。 You can follow this answer from stack overflow

答案 3 :(得分:0)

使用ObjectMapper窗格。

class GooglePlace : Mappable {

    var id = ""
    var addressTitle = ""
    var formattedAddress = ""
    var latitude : Double?
    var longitude : Double?

 required init?(map: Map) {

    }

    func mapping(map: Map) {
        addressTitle <- map["name"]
        formattedAddress <- map["formatted_address"]
        latitude <- map["geometry.location.lat"]
        longitude <- map["geometry.location.lng"]
        id <- map["id"]
    }

}

var placesesSearchHistory : [GooglePlace]? = []

if let jsonString = placesesSearchHistory?.toJSONString(prettyPrint: true) {
//Store in UserDefaults
      UserDefaults.standard.set(jsonString, forKey: "addressSearchHistory")

} 


//retrieve from UserDefaults
 if let dataArrayString = (UserDefaults.standard.string(forKey: "addressSearchHistory")) as? String {

 if let dataObject = Mapper<GooglePlace>().mapArray(JSONString: dataArrayString)  {
                placesesSearchHistory = dataObject
            }
        }