NSUserDefaults.standardUserDefaults()。stringForKey(“useremail”)返回null

时间:2017-07-25 12:18:57

标签: ios swift nsuserdefaults

我正在创建登录注册页面但是有错误。我尝试登录时,userStoredEmailuser和userStoredPassword返回null。请帮助解决此错误。

登录代码:

let useremail=email.text;
let userpassword=password.text;

let userStoredEmail = NSUserDefaults.standardUserDefaults().stringForKey("useremail") //return null

let userStoredPassword = NSUserDefaults.standardUserDefaults().stringForKey("userpassword") //return null

// print(emails);
//  print(userStoredEmail);

注册码:

let useremail=email.text;
let userpassword=password.text;
let userRePassword = RePassword.text;
//check for empty field

//store data

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("useremail", forKey: useremail!)
defaults.setObject("userpassword", forKey: userpassword!)
defaults.synchronize()

let alert1 = UIAlertController(title: "Alert", message:"Registration is succesfully complete", preferredStyle:.Alert)
// add an action (button)

alert1.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

presentViewController(alert1, animated: true, completion: nil)

2 个答案:

答案 0 :(得分:4)

不是

defaults.setObject("useremail", forKey: useremail!)
defaults.setObject("userpassword", forKey: userpassword!)

是的,你错误地将值保存到userdefaults

defaults.setObject(useremail!, forKey: "useremail")
defaults.setObject(userpassword!, forKey: "userpassword")

不需要synchronize() - 它会自动更新用户默认

答案 1 :(得分:2)

您正在存储"键"作为NSUserDefaults中的值,因此您需要写为

defaults.setObject(useremail!, forKey:"useremail")
defaults.setObject(userpassword!, forKey:"userpassword")

而不是

defaults.setObject("useremail", forKey: useremail!)
defaults.setObject("userpassword", forKey: userpassword!)