445
votes

How do I get a reference to the app delegate in Swift?

Ultimately, I want to use the reference to access the managed object context.

18
Note that some would consider use of the app delegate as a container for the managed object context or other "global" objects to be an anti-pattern. Consider having the app delegate pass the MOC to the controller, rather than making the controller find it.Kristopher Johnson
@KristopherJohnson Hey Kris, how can I facilitate the AppDelegate injecting dependencies into view controllers? Instantiate the view controller programatically and use reflection to decide what to instantiate / inject, recursively? Are there any frameworks that can help with this? If I have to do this for every view controller manually, my AppDelegate is going to be huge! Oh, preferably without creating a factory for everything :)Jimbo
A cursory search found Swinject which also has auto-wiring :)Jimbo
For programmers who advise against putting anything "extraneous" in the app delegate, it's a bit nonsense because the Apple documentation explicitly states that a "crucial role" of the UIApplicationDelegate singleton is "...to store your app’s central data objects or any content that does not have an owning view controller." developer.apple.com/documentation/uikit/uiapplicationdelegateliquid

18 Answers

803
votes

The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. In Swift 3, 4 & 5, this is done as follows:

let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
48
votes

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}
28
votes

Convenience Constructors

Add in AppDelegate Class at the end of code

Swift 5

func appDelegate() -> AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
}

To use AppDelegate reference in your class?


Call AppDelegate Method

appDelegate().setRoot()

22
votes

This could be used for OS X

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = appDelegate.managedObjectContext?
19
votes

It's pretty much the same as in Objective-C

let del = UIApplication.sharedApplication().delegate
14
votes

Here is the Swift 5 version:

let delegate = UIApplication.shared.delegate as? AppDelegate

And to access the managed object context:

    if let delegate = UIApplication.shared.delegate as? AppDelegate {

        let moc = delegate.managedObjectContext
        
        // your code here
        
    }

or, using guard:

    guard let delegate = UIApplication.shared.delegate as? AppDelegate  else {
        return
    }

    let moc = delegate.managedObjectContext
        
    // your code here
    
12
votes

Appart from what is told here, in my case I missed import UIKit:

import UIKit
10
votes

SWIFT < 3

Create a method in AppDelegate Class for ex

func sharedInstance() -> AppDelegate{
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

and call it some where else for ex

let appDelegate : AppDelegate = AppDelegate().sharedInstance()

SWIFT >= 3.0

func sharedInstance() -> AppDelegate{
    return UIApplication.shared.delegate as! AppDelegate
}
7
votes

Try simply this:

Swift 4

// Call the method
(UIApplication.shared.delegate as? AppDelegate)?.whateverWillOccur()

where in your AppDelegate:

// MARK: - Whatever
func whateverWillOccur() {

    // Your code here.

}
6
votes
  1. Make sure you import UIKit

  2. let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

5
votes

Here's an extension for UIApplicationDelegate that avoids hardcoding the AppDelegate class name:

extension UIApplicationDelegate {

    static var shared: Self {    
        return UIApplication.shared.delegate! as! Self
    }
}

// use like this:
let appDelegate = MyAppDelegate.shared // will be of type MyAppDelegate
4
votes

it is very simple

App delegate instance

let app = UIApplication.shared.delegate as! AppDelegate

you can call a method with one line syntax

app.callingMethod()

you can access a variable with this code

app.yourVariable = "Assigning a value"
2
votes

In my case, I was missing import UIKit on top of my NSManagedObject subclass. After importing it, I could remove that error as UIApplication is the part of UIKit

Hope it helps others !!!

2
votes

I use this in Swift 2.3.

1.in AppDelegate class

static let sharedInstance: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

2.Call AppDelegate with

let appDelegate = AppDelegate.sharedInstance
2
votes
extension AppDelegate {

    // MARK: - App Delegate Ref
    class func delegate() -> AppDelegate {
        return UIApplication.shared.delegate as! AppDelegate
    }
}
1
votes

In Swift 3.0 you can get the appdelegate reference by

let appDelegate = UIApplication.shared.delegate as! AppDelegate
1
votes

As of iOS 12.2 and Swift 5.0, AppDelegate is not a recognized symbol. UIApplicationDelegate is. Any answers referring to AppDelegate are therefore no longer correct. The following answer is correct and avoids force-unwrapping, which some developers consider a code smell:

import UIKit

extension UIViewController {
  var appDelegate: UIApplicationDelegate {
    guard let appDelegate = UIApplication.shared.delegate else {
      fatalError("Could not determine appDelegate.")
    }
    return appDelegate
  }
}
0
votes

In the Xcode 6.2, this also works

let appDelegate = UIApplication.sharedApplication().delegate! as AppDelegate

let aVariable = appDelegate.someVariable