Search code examples
iosswiftnsuserdefaults

NSUserDefault Value found nil with kill the App


I just trying to save the user Id and status as true value in UserDefaults when they login or Register with App.

UserDefaults.standard.set(user?.CustID, forKey: "CustID")
UserDefaults.standard.set(true, forKey: "status")

so when the user reopen the app in my Appdelegate I check the Status if it's true then user directly pass on HomeScreen and if the status False its pass on login screen.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

         let status = UserDefaults.standard.bool(forKey: "status")

        if (status == true) && (custID != "") {
            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "HomeTicketViewController") as! HomeTicketViewController
            let navigationController = UINavigationController(rootViewController: nextViewController)
            let appdelegate = UIApplication.shared.delegate as! AppDelegate
            appdelegate.window!.rootViewController = navigationController
        }else {
            let storyBoard : UIStoryboard = UIStoryboard(name: "Login", bundle:nil)
            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
            let navigationController = UINavigationController(rootViewController: nextViewController)
            let appdelegate = UIApplication.shared.delegate as! AppDelegate
            appdelegate.window!.rootViewController = navigationController
        }
}

I get the status true but i found that The CustID found nil. Is there any solution for that?


Solution

  • In userdefault if value not found in userdefaults corresponding to key then userdefault return nil and in case of bool it returns false.

    In your case, when you app launches, app does not have any value corresponding to custID so you getting nil.

    You need to add check like this

    if (status == true) && (custID != nil){
        :
        :
    }