Accessing custom AppDelegate properties from a ViewController using iOS and Swift

When creating iOS applications the AppDelegate (a sub-class of UIApplicationDelegate) typically handles the loading of the model and custom controllers.

To access a custom controller from a ViewController, you can set an instance of the custom controller as a property of the ApplicationDelegate and use the sharedApplication method of UIApplication class to access the property.

In Swift, the delegate property of the UIApplication.sharedApplication is an optional, so you will need to unwrap the optional value using the '!' operator. As well, since you are access a custom property of AppDelegate, you will need to cast the UIApplicationDelegate returned by UIApplication.sharedApplication.delegate as AppDelegate.

Step 1: Define the Custom Controller

import Foundation

class CustomController: NSObject {
// declare a text property for the CustomController
  let text = "A custom controller"

  // define a method that logs the value of the text property
  func performAction() {

Step 2: Instantiate the CustomController in the AppDelegate

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {

  var window: UIWindow?
  var cc: CustomController?

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Instantiate the CustomController when the application launches
    cc = CustomController()
    return true
  ... more

Step 3: Reference the CustomController using UIApplication.sharedApplication in the ViewController

import UIKit

class ViewController: UIViewController {

  override func viewDidLoad() {
    // Get the AppDelegate
    let appDel = UIApplication.sharedApplication().delegate! as AppDelegate
    // Call a method on the CustomController property of the AppDelegate

... more