Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: How should the App Delegate get a reference to the View Controller?

Tags:

xcode

ios

swift

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.

like image 814
Alan Avatar asked Feb 22 '15 19:02

Alan


People also ask

What is app delegate in Swift?

The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system. Like the UIApplication object, UIKit creates your app delegate object early in your app's launch cycle so it's always present.


1 Answers

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")
        }
    }
}
like image 122
Alan Avatar answered Nov 14 '22 22:11

Alan