How to link to AppDelegate from Today View widget?

So, I have a Today View widget built from my main application, and I'm trying to access some saved data (via CoreData). But when I create a lazy variable to process one of my entities, it does not 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 is displayed on line 2 on ... "as AppDelegate", which is "Undeclared use of AppDelegate". I think it makes sense, because AppDelegate is located in the folder of the base application, and not in the widget folder. But I am losing the opportunity to replace or fix this so that the code compiles and functions. Any ideas?

+5
source share
1 answer

You can not. Extensions are completely separated by binary files from the main application package in which your application delegate is located. You will have to either create a shared library that will be used by your main application package and extension, or make a lot of code for copying (the first method is preferred).

In the developer guides :

You can create an embedded infrastructure for code sharing between your extension application and the containing application. For example, if you create an image filter for use in the Photo Editing extension, as well as in its containing application, puts the filter code in the structure and embeds it for both purposes.

You do not need to create an official linked library if you do not want to. Just make sure the library you are writing does not reference APIs that are not available for extensions.

Make sure that the built-in framework does not contain APIs that are not accessible for application extensions, as described in Some APIs that are not available for an Application extensions . If you have a custom infrastructure that contains such APIs, you can safely reference it from your application, but cannot use this code with applications that contain extensions. The App Store rejects any application extension that associates with such structures or that otherwise uses inaccessible APIs.

+2
source

Source: https://habr.com/ru/post/1212074/


All Articles