7

I have a simple app with a loading screen. Here I check for some user details in NSUserDefaults and jump to either the login or the sign up screen.

The viewDidLoad() for the loading screen looks like this:

override func viewDidLoad()
{
    super.viewDidLoad()

    loadingVM = LoadingVM() as LoadingVM

    print("LoadingVC")
    checkStoredUser()
}

Here is the checkStoredUser()

func checkStoredUser()
{
    storedUserStatus = loadingVM.returnStoredUserStatus()

    if(storedUserStatus == true)
    {
        performSegueWithIdentifier("loadingToLoginVC", sender: self)
    }
    else
    {
        performSegueWithIdentifier("loadingToSignUpVC", sender: self)
    }
}

As you can see, I decide where to go from here based on what the loadingVM.returnStoredUserStatus() returns. I am sure this returns what it's supposed to return but nothing happens.

Here is the prepareForSegue()

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
    print("prepareForSegue")

    if(segue.identifier == "loadingToSignUpVC")
    {
        let signUpViewCotroller = (segue.destinationViewController as! LocalSignUpVC)
    }
    else if(segue.identifier == "loadingToLoginVC")
    {
        print("loadingToLoginVC")

        let loginViewCotroller = (segue.destinationViewController as! LoginVC)
    }
}

I did some digging and found a weird suggestion that seems to be working but It's not very practical not to mention right to do it like this:

func checkStoredUser()
{
    storedUserStatus = loadingVM.returnStoredUserStatus()

    let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
    dispatch_after(delayTime, dispatch_get_main_queue())
    {
        if(self.storedUserStatus == false)
        {
            self.performSegueWithIdentifier("loadingToSignUpVC", sender: self)
        }
        else
        {
            self.performSegueWithIdentifier("loadingToLoginVC", sender: self)
        }
    }
}

Can anyone explain to me what's going on here, why doesn't this work and how to make it work properly? It's the first time I encounter this and I can't seem to be able to find any info on this.

1 Answer 1

18

EXPLANATION:

Your View hasn't appeared yet when you call your checkStoredUser().

EASY FIX:

Put it in viewDidAppear() like this:

override func viewDidAppear(animated:Bool) {
    super.viewDidAppear(false)
    checkStoredUser()
}
1
  • That was simple :)). I thought that if I can call a function from viewDidLoad, say doStuff(), it would be OK to perform a segue from doStuff() but I guess it makes sense. Thanks
    – daydr3am3r
    Commented May 20, 2016 at 6:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.