0

I am trying to detect if the app is being opened for the first time. I've put this piece of code in my ViewController's viewDidLoad()

override func viewDidLoad() {
        super.viewDidLoad()

        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if launchedBefore  {
            performSegue(withIdentifier: "toMainController", sender: self)
            print("launchedBefore")
        } else {
            performSegue(withIdentifier: "toTutorialController", sender: self)
            UserDefaults.standard.set(true, forKey: "launchedBefore")
            print("not launchedBefore")

        }
    }

But, whenever the ViewController launches, no segues are performed. But thext I told it to print, is printed. If it matters, the view that the segue "toMainController" goes to is a UITabViewController, and the view that the segue "toTutorialController" goes to is just a UIViewController.

Does anyone have any ideas why this isn't working?

UPDATE

I found this error

2017-06-30 09:02:32.984 AppName[29732:24744712] Warning: Attempt to present on < AppName.ViewController: 0x7fcbfa908ed0> whose view is not in the window hierarchy!

Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47

3 Answers3

1

First save in userDefault and then perform segue:-

override func viewDidLoad() {
        super.viewDidLoad()

        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if launchedBefore  {
            performSegue(withIdentifier: "toMainController", sender: self)
            print("launchedBefore")
        } else {
            UserDefaults.standard.set(true, forKey: "launchedBefore")
            performSegue(withIdentifier: "toTutorialController", sender: self)
            print("not launchedBefore")
        }
    }
Ishika
  • 2,187
  • 1
  • 17
  • 30
1
override func viewDidLoad() {
        super.viewDidLoad()
      DispatchQueue.main.async {
        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if launchedBefore  {
            performSegue(withIdentifier: "toMainController", sender: self)
            print("launchedBefore")
        } else {
            UserDefaults.standard.set(true, forKey: "launchedBefore")
            performSegue(withIdentifier: "toTutorialController", sender: self)
            print("not launchedBefore")
        }
    }
  }
0

I figured it out. The problem wasn't the code itself, it was just where it was being executed. It needed to be executed in the UITabBarViewController.

Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47