2017-07-25 55 views
0

我正在創建登錄註冊頁面,但有錯誤。當我嘗試登錄時,userStoredEmailuser和userStoredPassword返回null。請幫助解決這個錯誤。NSUserDefaults.standardUserDefaults()。stringForKey(「useremail」)返回值爲空的值

登錄代碼:

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); 

Registreration代碼:

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) 
+0

,你叫這個'讓userStoredEmail = NSUserDefaults.standardUserDefaults()。stringForKey(「useremail」)// return null' in viewdidload or else ' –

+0

'key value for key property – karthikeyan

+0

在IBAction onclick按鈕我稱這userstroedEmail @ anbu.karthik –

回答

4

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

是,你被錯誤保存價值userdefaults

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

沒有必要的synchronize() - 它會自動更新userdefaults

+0

我很高興看到不需要同步的好建議。太多的人在不瞭解它的功能的情況下使用它(而不是)。 +1 – Moritz

+0

@Moritz - 非常感謝和歡迎 –

2

你存儲的 「鑰匙」 作爲值NSUserDefaults,所以你需要編寫爲

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

,而不是

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