David David - 3 months ago 17
Swift Question

Xcode; Set initial ViewController depending on if user data in NSUserDefaults or not

I'm developing an iOS app with Xcode and Swift.

After first launch user have to register and login. Register/Login ViewController is initial ViewController.

How can I set another ViewController as initial ViewController depending on if user data are already stored in NSUserDefaults or not. I think I'll have to do that in AppDelegate.swift, right?

This it the working code:

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

if NSUserDefaults.standardUserDefaults().objectForKey("username") != nil{

self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initialViewController = storyboard.instantiateViewControllerWithIdentifier("MainVC")

self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
}
// Override point for customization after application launch.
return true
}

Answer

You are almost there, just make two view controllers

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    let initialViewController: UIViewController?
    if NSUserDefaults.standardUserDefaults().objectForKey("username") != nil{
        // not registered
        initialViewController = storyboard.instantiateViewControllerWithIdentifier("RegisterVC")
    }
    else {
         // registered
        initialViewController = storyboard.instantiateViewControllerWithIdentifier("HomeVC")
    }

    self.window?.rootViewController = initialViewController!
    self.window?.makeKeyAndVisible()
    // Override point for customization after application launch.
    return true
}