简体   繁体   中英

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?

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){
    :
    :
}

The default is false

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

so status will be false at first , also status being true doesn't mean CustID saved no nil

UserDefaults.standard.set(user!.CustID, forKey: "CustID")

as user may be nil so force-unwrap to verify that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM