发现NSUserDefault值无效并杀死该应用程序

时间:2019-03-20 11:30:02

标签: ios swift nsuserdefaults

我只是试图在用户登录或向App注册时将用户ID和状态保存为UserDefaults中的真实值。

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

因此,当用户在我的Appdelegate中重新打开应用程序时,我会检查状态是否为true,然后用户直接通过HomeScreen,如果状态为False,则会在登录屏幕上通过。

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

我的状态为true,但是我发现CustID找不到n。 有什么解决办法吗?

2 个答案:

答案 0 :(得分:2)

userdefault中,如果在userdefaults中找不到与键相对应的值,则userdefault返回nil,如果为bool,则返回false

以您为例,当您启动应用程序时,该应用程序没有与 custID 相对应的任何值,因此您获得了nil

您需要像这样添加支票

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

答案 1 :(得分:1)

默认为false

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

因此状态一开始将为false,状态为true并不意味着CustID不保存nil

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

由于用户可能为零,因此请强制展开以确认