3

how to present view controller from appdelegate or scenedelegate in swift5 ? i tried this but didnt work :

self.window = UIWindow(frame: UIScreen.main.bounds)
                let storyboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewController = storyboard.instantiateViewController(withIdentifier: "profile")
                self.window?.rootViewController = initialViewController
                self.window?.makeKeyAndVisible()
alina
  • 107
  • 8
  • See https://stackoverflow.com/a/58208876/1226963 for an example. – rmaddy Oct 30 '19 at 16:53
  • But if you are using a storyboard, why are you adding code to show it? No code is needed for the main storyboard to be shown automatically on app startup. – rmaddy Oct 30 '19 at 16:55
  • 1
    What do you mean by "it didn't work"? What is the error message? – Sweeper Oct 30 '19 at 16:57
  • no i want present view controller programmatically from appdelegate or scenedelegate . @rmaddy – alina Oct 30 '19 at 16:57

2 Answers2

3

The problem is you're initializing the window's root view controller as the instantiated storyboard view. You need to set your window's root view like so:

    self.window?.rootViewController = ProfileViewController()

This sets it directly to the swift file, which should be a UIViewController of some sort, and doesn't use the Storyboard.

drfalcoew
  • 615
  • 5
  • 14
1

Make sure to initialize your view controller.

window?.rootViewController = ViewController() 

Are you doing this in SceneDelegate? If so, you can initialize your window with a windowScene

Source: https://youtu.be/2oo0tO1E9ys

shmathur
  • 59
  • 2