479

How do I get a reference to AppDelegate in Swift?

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

4
  • 9
    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. Jun 4, 2014 at 19:49
  • 1
    @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
    Mar 3, 2018 at 19:35
  • 1
    A cursory search found Swinject which also has auto-wiring :)
    – Jimbo
    Mar 3, 2018 at 19:41
  • 11
    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/uiapplicationdelegate
    – trndjc
    Sep 22, 2018 at 8:57

18 Answers 18

839

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
16
  • 11
    In case anyone is still having problems, targeting OS X requires you to import Cocoa for this to work for NSApplication.sharedApplication(). I'd guess that iOS would need the equivalent.
    – smaurice
    Jun 9, 2014 at 20:47
  • 2
    This is the more useful of the two answers.
    – Joe
    Jun 14, 2014 at 14:25
  • 3
    @zacjordaan Using that method, you will get autocompletion for the property, but it won't actually work. That way will create a new instance of the AppDelegate class every time you use it. You're better off using the delegate accessible through the sharedApplication singleton. And as far as your second question goes, yes you probably want to use a constant. Even though, you may be changing the AppDelegate's properties, you probably won't be reassigning the pointer to anything else, in which case, there's no need for a variable. This is completely up to you though. Do what suits your needs. Jun 27, 2014 at 13:30
  • 2
    Excellent advice! I had mistakenly thought that AppDelegate() was singleton but after thinking about what you've said I've realized that if it was then there wouldn't be a sharedApplication pattern for us to use in this way. Of course I don't want to spawn unnecessary instances if I don't have to, so your constant declaration will suit perfectly; Thank you.
    – zacjordaan
    Jun 27, 2014 at 14:07
  • 5
    I don't want to add this as separate answer, but to get AppDelegate with your own methods, properties in project where both a Swift and an Obj-c are used You should add #import "AppDelegate.h" to "ProjectName-BridgingHeader.h" Feb 8, 2019 at 11:19
54

Swift 4.2

In Swift, easy to access in your VC's

extension UIViewController {
    var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate
   }
}
0
40

Convenience Constructors

Add in AppDelegate Class at the end of code

Swift 5.7

 func appDelegate() -> AppDelegate {
    guard let delegate = UIApplication.shared.delegate as? AppDelegate else {
        fatalError("could not get app delegate ")
    }
    return delegate
 }

To use AppDelegate reference anywhere in code?


For example: Call AppDelegate Method named setRoot

appDelegate().setRoot()

Scene Delegate Example:

func sceneDelegate() -> SceneDelegate {
    guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate else {
      fatalError("could not get scene delegate ")
    }
   return sceneDelegate
}
2
  • 2
    Would be great to explain what setRoot() does and when to call it. e.g. is it ok to call it from a ViewController? From a Unit test where window is not set yet? More context would be great.
    – Houman
    Dec 24, 2019 at 16:52
  • @Houman setRoot is method from AppDelegate which could be used to switch between multiple Roots or ParentViewController and could be any method. Discussion is about how to get the reference of AppDelegate to further access, but hope setRoot must be clear as well.
    – AiOsN
    Dec 26, 2019 at 5:46
24

This could be used for OS X

let appDelegate = NSApplication.sharedApplication().delegate as AppDelegate
var managedObjectContext = appDelegate.managedObjectContext?
4
  • 3
    Or simply let appDelegate = NSApp.delegate as AppDelegate Jun 28, 2016 at 7:52
  • 1
    In Swift 3 use let appDelegate = NSApplication.shared().delegate as AppDelegate
    – Dirk
    Mar 4, 2017 at 23:41
  • 4
    In Swift 4: NSApp.delegate as? AppDelegate
    – Nick
    Jun 6, 2018 at 11:55
  • 2
    updated for swift 5* NSApplication.shared.delegate as? AppDelegate
    – Roshan Sah
    Jan 8, 2021 at 11:48
21

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

let del = UIApplication.sharedApplication().delegate
17

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
    
15

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

import UIKit
1
  • this fixed my issue for the error Cannot find 'UIApplication' in scope
    – Marlhex
    Feb 7, 2022 at 6:08
12

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
}
5
  • 2
    this also works, and i like the idea of the sharedInstance naming. thanks! Jun 22, 2016 at 1:03
  • 2
    Your example would still instantiate a new AppDelegate object every time you called AppDelegate().sharedInstance() Nov 13, 2016 at 6:37
  • 1
    I like this solution better than the accepted one (which is "unsiwftly" verbose if you have to use it all over). I was thinking about experimenting with an extension for NSApplication before I found this answer, but this is much better. Nowadays you would probably want to use a class computed read only property shared though, maybe you would like to post an update for Swift 3?
    – Patru
    May 25, 2017 at 23:41
  • 1
    I am actually in the process of refactoring my code to use static var shared : TournamentDelegate? { get { return NSApplication.shared().delegate as? TournamentDelegate } } which is more in line with the developing Swift 3 style of using computed read only properties for this type of things. I will probably be able to drop the ? once the refactoring is done, don't you think? (Sorry, code formatting in comments is always a mess.)
    – Patru
    May 26, 2017 at 7:25
  • @ pxpgraphics UIApplication is a singleton class so no need to worry about multiple instantiation.
    – Abhijith
    Dec 4, 2017 at 9:57
8

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.

}
7

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
2
  • on the Mac for NSApplicationDelegate this gives me: 'Self' is only available in a protocol or as the result of a method in a class; did you mean 'AppDelegate'?. Is this outdated?
    – pkamb
    Nov 5, 2019 at 23:03
  • @pkamb I've just tried it in a new project and I don't have this error. I replaced UIApplicationDelegate by NSApplicationDelegate and UIApplication by NSApplication.
    – nyg
    Nov 7, 2019 at 18:52
7
  1. Make sure you import UIKit

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

5

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"
4
extension AppDelegate {

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

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 !!!

3

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

In Swift 3.0 you can get the appdelegate reference by

let appDelegate = UIApplication.shared.delegate as! AppDelegate
2

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
  }
}
2
  • 1
    In swift5 your code will give "UIApplication.delegate must be used from main thread only" warning. Can you update answer. Jul 18, 2019 at 8:19
  • 3
    that fatalError is functionally equivalent to a force unwrap!
    – pkamb
    Nov 5, 2019 at 23:00
1

In the Xcode 6.2, this also works

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

let aVariable = appDelegate.someVariable
1
  • 2
    v01d, from where you have taken that ?
    – NSPratik
    Dec 29, 2015 at 13:42

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.