Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference the AppDelegate from a Today View Widget?

So I have a Today View widget built off of my main application, and I'm trying to access some stored data (via CoreData). But when I am creating the lazy variable to handle one of my entities, it fails to compile. I understand the error that it throws, but I'm not sure how to handle/fix it.

lazy var managedObjectContext : NSManagedObjectContext? = {
    let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    if let managedObjectContext = appDelegate.managedObjectContext {
        return managedObjectContext
    }
    else {
        return nil
    }
    }()

The error gets thrown at on line 2 at ..."as AppDelegate" that it is an "Undeclared use of AppDelegate." Which I guess makes sense because AppDelegate is in the base application folder and not in the widget's folder. But I am at a loss of how to replace or repair this so that the code will compile and function. Any ideas?

like image 702
tuckerchapin Avatar asked Oct 31 '22 10:10

tuckerchapin


1 Answers

You can't. Extensions are entirely separated binaries from your main app bundle, which is where your app delegate resides in. You will have to either make a shared library that will be used by your main app bundle and extension, or do a lot of copy-pasting code (the former method is preferred).

From the developer guides:

You can create an embedded framework to share code between your app extension and its containing app. For example, if you develop an image filter for use in your Photo Editing extension as well as in its containing app, put the filter’s code in a framework and embed the framework in both targets.

You don't have to create a formal linkable library if you don't want. Just make sure that the library you are writing doesn't reference APIs that are not available for extensions.

Make sure your embedded framework does not contain APIs unavailable to app extensions, as described in Some APIs Are Unavailable to App Extensions. If you have a custom framework that does contain such APIs, you can safely link to it from your containing app but cannot share that code with the app’s contained extensions. The App Store rejects any app extension that links to such frameworks or that otherwise uses unavailable APIs.

like image 189
Andy Ibanez Avatar answered Nov 12 '22 15:11

Andy Ibanez