我想让一个客户注册,在输入数据后,它被映射到一个用户的默认值,并保存在那里,当我想验证用户时,我调用一个函数Verify,从用户中获取保存的数据,以验证用户,但GET中的数据映射不起作用。
var UserInfoDefualts: UserModel {
set {
let userJson = try! JSONEncoder().encode(newValue)
let jsonString = String(data: userJson, encoding: .utf8)!
KeychainWrapper.standard.set(jsonString, forKey: "UserData")
}
get {
let userJosn = KeychainWrapper.standard.string(forKey: "UserData") ?? ""
let userData = Mapper<UserModel>().map(JSONString: userJosn) ?? UserModel()
return userData
}
}
get没有映射数据userdata总是NIL,而在teh set中,它的Filled是正确的。
注册功能
@IBAction func continueButtonClicked(_ sender: UIButton) {
ApiServices.shared.signUp(name: fullName.text!, number: phoneNumber.text!, gender: 1, date: birthDate.text!) { (result, statusCode) in
print(result)
if statusCode == 200 {
let userData = result
print(userData.fullName)
UserInfoDefualts = userData
ScreenLoader().pushVC(rootView: self, viewController: Verify_VC)
// Shared.logIn(userData: userData)
}
}
}
验证功能
@IBAction func verifyClicked(_ sender: Any) {
var data = UserInfoDefualts
ApiServices.shared.verifyUser(userID: UserInfoDefualts.userId ?? 0, otpCode: self.code) { (result, statusCode) in
if statusCode == 200 {
ScreenLoader().pushVC(rootView: self, viewController: Welcome_VC)
}
}
}
在结构中替换 Encodable
与 Codable
并删除所有与 ObjectMapper
然后将计算出的属性替换为
var userInfoDefaults: UserModel? {
set {
let userJson = try! JSONEncoder().encode(newValue!)
let jsonString = String(data: userJson, encoding: .utf8)!
KeychainWrapper.standard.set(jsonString, forKey: "UserData")
}
get {
guard let userJosn = KeychainWrapper.standard.string(forKey: "UserData") else { return nil }
let data = Data(userJosn.utf8)
do {
return try JSONDecoder().decode(UserModel.self, from: data)
} catch {
print(error)
return nil
}
}
}
作为 UserModel
没有自定义的初始化器,计算的属性必须是一个可选的。所以你必须在IBAction中写下
guard let data = userInfoDefaults else { return }
你可以将objectmapper对象存储在用户默认中,如下所示。
if let userInfo = Mapper<SignInModel>().map(JSONObject: dictionary["signup"]) {
if let JSONString = Mapper().toJSONString(userInfo, prettyPrint: true) {
//User Info:-
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: JSONString)
UserDefaults.standard.set(encodedData, forKey: "userinfo")
}