我的NSUserDefaults代码不起作用

时间:2016-06-25 05:46:19

标签: ios swift swift2 nsuserdefaults

我很快乐。需要你的帮助! 我想要的是,当用户第二次登录时,应用程序应该直接将其带到名为CoreView的下一个视图控制器。它不应该要求细节,但我不知道为什么它不起作用。并且每次启动应用程序时都会询问详细信息。请检查以下代码。我也没有得到任何错误。除非并且直到应用程序被终止或注销,否则用户应该能够直接登录。

$http

在viewDidLoad函数中:

func pref_write()
{
    // To write the  data to NSUserDefaults

    let prefs = NSUserDefaults.standardUserDefaults() // make a reference
    print("OTP:\(OTP)")

    // Adding values. Creating objects in prefs
    prefs.setObject(OTP, forKey: "OTP")
    print("check_OTP:\(check_OTP)")

    prefs.setObject(U_ID, forKey: "U_ID")
    print("Check_U_ID:\(check_U_ID)")
    prefs.synchronize()
    self.performSegueWithIdentifier("ContinueToCoreView", sender: self)

}

谢谢!

2 个答案:

答案 0 :(得分:1)

创建一个类

class User_Details : NSObject
{
    var user_id : String?
    var user_otp : String?
    var otp_verified : Bool?

    init(u_id:String, otp:String?, verified:Bool)
    {
        super.init()
        self.user_id = u_id
        self.otp_verified = verified
        self.user_otp = otp
    }
}

AppDelegate 中,

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    navController = self.window?.rootViewController as? UINavigationController
    if self.checkIfUserLoggedIn()
    {
        let user_details = NSUserDefaults.standardUserDefaults().objectForKey("user_details") as! User_Details
        self.moveToNextScreen(user_details)
    }
    return true
}

//AppDelegate Class or in the class which is globally accessible
func pref_write_user(user_details : User_Details)
{
    let prefs = NSUserDefaults.standardUserDefaults()
    prefs.setObject(user_details, forKey: "user_details")
    prefs.setBool(true, forKey: "is_user_login")

    //After saving the OTP for current user, check for otp verified, move to OTP Screen
    self.moveToNextScreen(user_details)
}

func moveToNextScreen(user_details : User_Details)
{
    if user_details.otp_verified == false
    {
        // Move to OTP screen
        let viewController = self.navController?.storyboard?.instantiateViewControllerWithIdentifier("otpScreen")
        self.navController?.pushViewController(viewController!, animated: false)
    }
    else // Move to Home Screen
    {
        let viewController = self.navController?.storyboard?.instantiateViewControllerWithIdentifier("homeScreen")
        self.navController?.pushViewController(viewController!, animated: false)
    }
}

func logoutUser()
{
    let prefs = NSUserDefaults.standardUserDefaults()
    prefs.setObject(nil, forKey: "user_details")
    prefs.setBool(false, forKey: "is_user_login")
}

func checkIfUserLoggedIn() -> Bool
{
    let prefs = NSUserDefaults.standardUserDefaults()

    if prefs.boolForKey("is_user_login")
    {
        if let _ = prefs.objectForKey("user_details")
        {
            return true
        }
        else
        {
            //User details not found for some reason, so setting the inital values and return false
            self.logoutUser()
        }
    }

    return false
}

登录类: 通过提供基本凭证调用API进行登录,获取user_id和user_otp,将它们保存到NSUserDefaults

func requestLoginToServer()
{
    //Perform basic server action
    ....
    //In Success Block write this
    let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
    // pass the values as return by the server
    let user_details = User_Details(u_id: "123", otp: "1234", verified: false) 
    appDel.pref_write_user(user_details)
    appDel.moveToNextScreen(user_details)
}

答案 1 :(得分:1)

请尝试这种方式。我只是重新安排了你的代码   首先,它将使用初始视图控制器的didload方法检查登录凭据。如果不存在,则会调用方法 pref_write()。请确保pref_write()方法中使用的值不是nil

override func viewDidLoad()
{
    super.viewDidLoad()

    let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    // You can give conditions for your need like  if(prefs.valueForKey("U_ID") != nil))
    // It will check the user defaults whether you already login
    if(prefs.valueForKey("OTP") != nil) {   

          self.performSegueWithIdentifier("ContinueToCoreView", sender: self)
    }

    else{

         pref_write()
    } 
}


 // Make sure the Values are not nil

 func pref_write()
 {
      // To write the  data to NSUserDefaults

      let prefs = NSUserDefaults.standardUserDefaults() // make a reference
      print("OTP:\(OTP)")

     // Adding values. Creating objects in prefs
      prefs.setObject(OTP, forKey: "OTP")
      print("check_OTP:\(check_OTP)")

      prefs.setObject(U_ID, forKey: "U_ID")
      print("Check_U_ID:\(check_U_ID)")
      prefs.synchronize()
      self.performSegueWithIdentifier("ContinueToCoreView", sender: self)

}

希望它的工作......