Mili Mili - 5 months ago 20
Swift Question

My code for NSUserDefaults is not working

I am very new to swift. And need your help!
I want that, when the user logs in for the second time , the app should directly take it to the next view controller named CoreView. It should not ask for details, but I don't know why its not working. And it's asking for details everytime the app is launched. Please check the below code. I am not getting any sort of error too. Unless and until the app is killed or logged out, the user should be able to log in directly .

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)

}


And in the viewDidLoad function:

override func viewDidLoad()
{

super.viewDidLoad()
//Read the data
self.performSegueWithIdentifier("ContinueToCoreView", sender: self)
pref_write()
let prefs = NSUserDefaults.standardUserDefaults()
check_OTP = prefs.objectForKey("OTP")!
check_U_ID = prefs.objectForKey("U_ID")!
prefs.objectForKey("U_ID")
print("prefs:\(prefs)")
prefs.synchronize()

}


Thanks!

Answer

Create a class as

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
    }
}

In 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
}

Login Class : Call the API for login by providing the basic credential, get the user_id and user_otp, save them to 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)
}
Comments