1

I'm trying to update the root view controller from ViewController() to fourYearPlan(). When the user initially opens the app, they are greeted in ViewController() and led to a TableViewController(). From there, when they tap on a tableViewCell, it will lead them to fourYearPlan() and automatically change the root view controller to it. If the user presses a button in fourYearPlan() the root view controller resets to ViewController(). How will I be able to approach this?

AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

    // MARK: UISceneSession Lifecycle

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    @available(iOS 13.0, *)
    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

    func updateRootVC(){

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

        print(status)

        if status == true {
            let navController = UINavigationController(rootViewController: fourYearPlan())
            window?.rootViewController = navController
        }
        else{
            let navController = UINavigationController(rootViewController: ViewController())
            window?.rootViewController = navController
        }
        window?.makeKeyAndVisible()
    }
}

Portion of SceneDelegate:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).  
        guard let _ = (scene as? UIWindowScene) else { return }
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window = window
        appDelegate.updateRootVC()

    }

ViewController() will lead to TableViewController() and if clicked, fourYearPlan becomes the new root view controller from ViewController():

     override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        let layout = UICollectionViewFlowLayout()
        let destination = fourYearPlan(collectionViewLayout: layout)

//        UserDefaults.standard.set(true, forKey: "status")
//        let appDelegate = UIApplication.shared.delegate as! AppDelegate
//        appDelegate.updateRootVC()


        navigationController?.pushViewController(destination, animated: true)

    }

button in fourYearPlan() that resets root view controller:

    @objc func addTapped(sender: UIBarButtonItem!) {
        let addAlert = UIAlertController(title: "Start Over", message: "Are you sure you want to create a new plan?", preferredStyle: .alert)


        addAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action:UIAlertAction) in
            let defaults = UserDefaults.standard

//            defaults.set(false, forKey: "status")
//            let appDelegate = UIApplication.shared.delegate as! AppDelegate
//            appDelegate.updateRootVC()

            let domain = Bundle.main.bundleIdentifier!
            defaults.removePersistentDomain(forName: domain)
            defaults.synchronize()


            let destination = ViewController()
            self.navigationController?.pushViewController(destination, animated: true)

        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)
    }
Liam
  • 27,717
  • 28
  • 128
  • 190
Paul Jung
  • 43
  • 1
  • 7
  • I don't understand. On button press in fourYearPlan(), you want to move to ViewController() or rootViewController? – PGDev Feb 21 '20 at 11:04
  • You are already using a navigation controller to "push" to `fourYearPlan` ... why not just `pop` back? Or, if you are going from `viewController()` to `tableViewController()` to `fourYearPlan` and you want to skip the table view and go directly back to the first view, you can use either `popToRootViewController()` or `popToViewController()` (and specify the target to pop to). – DonMag Feb 21 '20 at 13:29
  • @PGDev on a button press in fourYearPlan, I want to make ViewController() the new rootviewcontroller. And when the user first opens the app, they are greeted with viewcontroller() as the rootviewcontroller then transitions into tableviewcontroller() in which they click on a cell go to fourYearPlan() and makes the new rootviewcontroller as fourYearPlan(). – Paul Jung Feb 22 '20 at 01:13
  • @DonMag the `ViewController()` and `TableViewController()` is sort of like a login screen. I want the user to be greeted with `ViewController()` and `TableViewController()` when they first install and open the app only. After that, I want `fourYearPlan()` to be the inital root view contoller. – Paul Jung Feb 22 '20 at 01:17

1 Answers1

0

For Xcode 13+ , Swift 5+

Open SceneDelegate and paste replace this , Replace CustomerMainViewController with your view controller

   func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }

        if UserDefaultHelper.isLoggedIn! {
            print("User logged in")
            let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) // this assumes your storyboard is titled "Main.storyboard"
            let yourVC = mainStoryboard.instantiateViewController(withIdentifier: "CustomerMainViewController") as! CustomerMainViewController // inside "YOUR_VC_IDENTIFIER" substitute the Storyboard ID you created in step 2 for the view controller you want to open here. And substitute YourViewController with the name of your view controller, like, for example, ViewController2.
            self.window?.rootViewController = yourVC
            self.window?.makeKeyAndVisible()
        }
        else {
            print("User Not logged in")
        }
        
    }
Quick learner
  • 10,632
  • 4
  • 45
  • 55