How do you reference an Objective C AppDelegate from a Swift Class?

1.5k Views Asked by At

I have an Objective C project and am trying to call the AppDelegate from a Swift view controller. This code is not working:

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

let managedContext = appDelegate.managedObjectContext
3

There are 3 best solutions below

1
Adrian Sluyters On

Have you added the brining header to your project?

On top of that, if you do, make sure you import "AppDelegate.h" into the bridging header.

The in the swift class you should be able to call it with:

guard let appDele = UIApplication.sharedApplication().delegate as? AppDelegate else {
    fatalError("Unable to reference App Delegate, check settings and riding header")
}
let managedContext = appDele.managedObjectContext
0
Aron Nelson On

There is another way. Include "AppDelegate.h" into the bridging header and make sure you resolve any errors.

Then create an Objective C object that has one method that returns the app delegate object. All it needs to do is return the app delegate pointer. The object file must also include "AppDelegate.h" and resolve any errors.

-(yourAppDelegate*)giveMeTheAppDelegate{
 return yourAppDelegate;
}

Then in the Swift file, you can now create the object and reference any methods.

let theObj = iAmAnObjectiveCObjectWithOneMethod()
let theDelegate = theObj.giveMeTheAppDelegate()
theDelegate?.thisMethodDisplaysText("hello")
0
Sheetal Shinde On

Add "(ProjectName)-Swift.h" in .m file

Add @class AppDelegate in .h file

Add variables in AppDelegate file with '@objc' extension so that it can be accessed in Objective C as well as *** file.