Konrad Löchner Konrad Löchner - 1 month ago 9
Swift Question

open other view with segue only works by pressing button

I want to open an other view controller, after checking if it is the first run of the app.
It works when I press a button but not when I call the method openMap

class TutorialController: UIViewController {

override func viewDidLoad() {
//check if the app opens for the first time
if(UserDefaults.standard.bool(forKey: "HasLaunchedOnce"))
{
// app already launched
print("not first launch")
openMap()
}
else
{
// This is the first launch ever
UserDefaults.standard.set(true, forKey: "HasLaunchedOnce")
UserDefaults.standard.synchronize()
print("first launch")
openTutorial()
}
}
func openTutorial(){

}
@IBAction func openMap(){
print("openmap opened")
performSegue(withIdentifier: "openMap", sender: nil)

}


}

Answer

I assume, you've connected your button to @IBAction func openMap() if so, you should not call openMap() action inside your viewDidLoad, but use the same code performSegue(withIdentifier: "openMap", sender: nil) instead in your viewDidAppear:

if(UserDefaults.standard.bool(forKey: "HasLaunchedOnce"))
    {
        // app already launched
        print("not first launch")
        performSegue(withIdentifier: "openMap", sender: nil)
    }
...

If it doesn't work, you've probably made a mistake with creation of your segue and have connected Button to the destination ViewController directly in your storyboard instead of connecting two controllers:segue between controllers

If so, just remove the old segue, and re-crete it in the way as it is on the image above and assign the same segue id "openMap"

EDITED: Please, move performing of your segue to the viewDidAppear instead of viewDidLoad, because viewDidLoad is called when the ViewController object is created and it's not yet attached to the window.