Show another view controller at the first launch and not again

江枫思渺然 提交于 2019-12-10 18:27:34

问题


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?


回答1:


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!



来源:https://stackoverflow.com/questions/32005900/show-another-view-controller-at-the-first-launch-and-not-again

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