How to present login screen only when a userdefaults key doesn't exist?

点点圈 提交于 2019-12-06 16:45:26

You just need to in the Appdelegate.swift's application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) method to judge.

But the precondition is you should manual operation the window:

Delete this line in your info.plist:

Then in your AppDelegate.swift you can set your window manually:

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

    self.window = UIWindow.init(frame: UIScreen.main.bounds)

    let sb:UIStoryboard = UIStoryboard.init(name: "Main", bundle: nil)

    let isLogin:Bool = UserDefaults.standard.bool(forKey: "isLogin")
    if isLogin {

        let vc2 = sb.instantiateViewController(withIdentifier: "ViewController2")

        self.window?.rootViewController = vc2
    }else {
        let vc1 = sb.instantiateViewController(withIdentifier: "ViewController")
        self.window?.rootViewController = vc1
    }

    self.window?.makeKeyAndVisible()

    return true
}

And in your ViewController.swift(you can regard it as LoginVc):

override func viewDidLoad() {
    super.viewDidLoad()

    /* add userdefaults */

    UserDefaults.standard.set(true, forKey: "isLogin")
    UserDefaults.standard.synchronize()

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!