Jacob Cavin
Jacob Cavin

Reputation: 2329

Error When Detection First Launch (Swift)

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!

Upvotes: 0

Views: 101

Answers (3)

user6930374
user6930374

Reputation:

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")
        }
    }
  }

Upvotes: 1

Jacob Cavin
Jacob Cavin

Reputation: 2329

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.

Upvotes: 0

Ishika
Ishika

Reputation: 2205

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")
        }
    }

Upvotes: 1

Related Questions