2016-05-16 88 views
1

我想保存用戶的會話與NSUserDefaults,如果用戶登錄,我會將NSUserDefaults設置爲true,反之亦然。但是,即使輸入了正確的憑證,我的用戶也永遠停留在登錄頁面上。我該如何解決它?視圖控制器的條件加載卡住在初始ViewController

LoginViewController代碼

func handlingAuthentication(notification: NSNotification) { 

    let dict = notification.object as! NSDictionary 
    let errorFound = dict["error"] 
    let errorMessage = dict["message"] 
    print(errorFound) 

    if(errorFound){ 
     //initialize Alert Controller 
     let alertController = UIAlertController(title: "Authentication error", message: errorMessage?.string, preferredStyle: .Alert) 

     //Initialize Actions 
     let okAction = UIAlertAction(title: "Ok", style: .Default){ 
       (action) -> Void in 
       self.dismissViewControllerAnimated(true, completion: nil) 
      } 

     //Add Actions 
     alertController.addAction(okAction) 

     //Present Alert Controller 
     self.presentViewController(alertController, animated: true, completion: nil) 

    } 
    else 
    { 
     NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn") 

     NSUserDefaults.standardUserDefaults().synchronize() 

     self.dismissViewControllerAnimated(true, completion:nil) 

    } 

} 

這是我調用該方法handlingAuthentication在LoginViewController

@IBAction func loginBtn(sender: AnyObject) { 
let loginobj = Login(userName : self.usernameField.text!, passWord : self.pwdField.text!) 
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(LoginViewController.handlingAuthentication(_:)), name:"errorPresent", object: nil) 
loginobj.getRequest() 
} 

HomeViewController代碼

override func viewDidAppear(animated: Bool) { 
    let isUserLoggedIn = NSUserDefaults.standardUserDefaults().boolForKey("IsUserLoggedIn") 
    if(!isUserLoggedIn){ 
     self.performSegueWithIdentifier("toLoginVC", sender: self) 
    } 
} 

@IBAction func logoutBtn(sender: AnyObject) { 
    NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isUserLoggedIn") 
    NSUserDefaults.standardUserDefaults().synchronize() 
} 
+0

handlingAuthentication如何調用此方法 –

+0

嗨@PKT我在我的LoginViewController中調用了我的方法(更新了我的帖子以顯示此內容) – noobdev

+0

請給出它卡住的行 –

回答

0

您正在使用不同的密鑰:

既然你存儲的關鍵「isUserLoggedIn」

NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn") 

isUserLoggedIn將永遠是假的,因爲你得到一個不同的密鑰「IsUserLoggedIn」

let isUserLoggedIn = NSUserDefaults.standardUserDefaults().boolForKey("IsUserLoggedIn") 
相關問題