Search code examples
swiftauthenticationrootviewcontroller

I want my already logged in users to have my ViewController3 as rootViewController and those who aren't logged in to have ViewController2


Does somebody know which code I should add to my project? The problem I also have is that I use pre-built log in VC, so I am unsure if I can use the same code as those who have built one themselves


Solution

  • Logged Users -> ViewController3 Not Logged Users -> ViewController2

    Check out this video https://www.youtube.com/watch?v=G5UkS4Mrepo at [24:38]

    You need to store a value in default user (Core Data / inside the device Phone). Based on this value feed or not you can redirect users proprely :

    Add this to your AppDelegate.swift :

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        window = UIWindow(frame: UIScreen.main.bounds)
        window = UIWindow(frame: UIScreen.main.bounds) 
        let sb = UIStoryboard(name: "ViewController3", bundle: nil)
        var initialViewController = sb.instantiateViewController(withIdentifier: "Onboarding")
        let userDefaults = UserDefaults.standard
        if userDefaults.bool(forKey: "LoginComplete") {
            initialViewController = sb.instantiateViewController(withIdentifier: "ViewController3")
        }
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
    

    Add this code to your login Viewcontroller3

        override func viewDidLoad() {
        let userDefaults = UserDefaults.standard
        userDefaults.set(true, forKey: "LoginComplete")
        userDefaults.synchronize()
    

    Remove the arrow (initial ViewController) from the mainstoryboard if any This assume that you ViewController2 is the initial VC