DHK
DHK

Reputation: 31

Show another view controller at the first launch and not again

I am making an application with swift that has two view controllers(main page, login page) and I want to show login page at the very first launch.

So I used this code.

class ViewController: UIViewController {

override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool {
    if identifier == "LoginSegue" {

        var segueShouldOccur : Bool

        let isFirst:Bool = NSUserDefaults.standardUserDefaults().boolForKey("isFirst")
        if isFirst == false
        {
            segueShouldOccur = true
            NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isFirst")
        }
        else {
            segueShouldOccur = false
        }

        if segueShouldOccur == true {
            println("*** NOPE, segue wont occur")
            return false
        }
        else {
            println("*** YEP, segue will occur")
        }
    }

    // by default, transition
    return true
}

override func viewDidLoad() {
    super.viewDidLoad()


}
   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

I used the segue with identifier "LoginSegue" to show login page. But with simulator it doesn't show login page. How can I show login page from the first launch?

Upvotes: 3

Views: 1188

Answers (1)

iRiziya
iRiziya

Reputation: 3245

You can write the required code in AppDelegate.swift file inside didFinishLaunchingWithOptions method

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {     

//SET INITIAL CONTROLLER
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        var initialViewController: UIViewController
        if() //your condition if user is already logged in or not
        {
           // if already logged in then redirect to MainViewController

            initialViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainController") as! MainViewController // 'MainController' is the storyboard id of MainViewController 
        }
        else
        {
           //If not logged in then show LoginViewController
            initialViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LoginController") as! LoginViewController // 'LoginController' is the storyboard id of LoginViewController 

        }

        self.window?.rootViewController = initialViewController

        self.window?.makeKeyAndVisible()
     return true
 }

Hope this will work!

Upvotes: 5

Related Questions