I know this question has been asked countless times already, and I've seen many variations including
func performSegue(withIdentifier identifier: String,
sender: Any?)
and all these other variations mentioned here: How to call a View Controller programmatically
but how would you change a view controller outside of a ViewController
class? For example, a user is currently on ViewController_A
, when a bluetooth device has been disconnected (out of range, weak signal, etc) the didDisconnectPeripheral
method of CBCentral
gets triggered. In that same method, I want to change current view to ViewController_B
, however this method doesn't occur in a ViewController
class, so methods like performSegue
won't work.
One suggestion I've implemented in my AppDelegate
that seems to work (used to grab the appropriate storyboard file for the iphone screen size / I hate AutoLayout
with so much passion)
var storyboard: UIStoryboard = self.grabStoryboard()
display storyboard
self.window!.rootViewController = storyboard.instantiateInitialViewController()
self.window!.makeKeyAndVisible()
And then I tried to do the same in my non-ViewController
class
var window: UIWindow?
var storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) //assume this is the same storyboard pulled in `AppDelegate`
self.window!.rootViewController = storyboard.instantiateViewController(withIdentifier: "ViewController_B")
self.window!.makeKeyAndVisible()
However I get an exception thrown saying fatal error: unexpectedly found nil while unwrapping an Optional value
presumably from the window!
Any suggestions on what I can do, and what the correct design pattern is?