6

I've started a new Swift project, I'm playing around with things to see how the wiring works with storyboards since I've never used them before.

The project is a single-view app using the default storyboard created by Xcode 6.1. It generates the AppDelegate.swift and ViewController.swift classes as well as Main.storyboard.

Btw, I'm kind of going off of this tutorial:

http://www.raywenderlich.com/74904/swift-tutorial-part-2-simple-ios-app

I've got things working with a button and a couple of textview controls that I added using the storyboard Interface Builder.

What I'd like to do now, is hook up the app delegate's application didFinishLaunching event to the view controller.

func application(application: UIApplication,
     didFinishLaunchingWithOptions launchOptions: 
     [NSObject: AnyObject]?) -> Bool {
}

I've found many StackOverflow articles discussing this, however the examples are all around instantiating your own view controller. I want to simply get a reference to the view controller that was launched via the storyboard.

What's the best way to do this? Feel free to point me to the appropriate docs, or other posts.

Alan
  • 3,715
  • 3
  • 39
  • 57
  • The AppDelgate always has a reference to the root view controller and can be referenced through the property AppDelegate.window.rootViewController – Literphor Feb 22 '15 at 19:36
  • 2
    Carefully consider doing what you are trying to do in the ViewController rather than the AppDelegate. A common issue is putting too much in the AppDelegate. It's job is to react to launch events and other external things that happen to your app. if you're doing much more than that, rethink your design. That said, @Litephor is correct. – picciano Feb 22 '15 at 20:11

1 Answers1

8

I finally found this article on checking the current view controller, which had the logic I was looking for:

var myViewController : ViewController!
...
if let viewControllers = self.window?.rootViewController?.childViewControllers {
    for viewController in viewControllers {
        if viewController.isKindOfClass(ViewController) {
            myViewController = viewController as ViewController
            println("Found the view controller")
        }
    }
}
Community
  • 1
  • 1
Alan
  • 3,715
  • 3
  • 39
  • 57