I am working on an app where I am using a Share Sheet to add the data to the main app. I am using Core data to store data in the main app and wanted the share sheet to have access to the same model and store so that I do not have to rely on notifications to pass data from the share sheet extension to the main app. It is an interesting problem with a simple enough solution.
The first step will be to add the main app and the extension to the same app group. Even though the app and extension are bundled together they do not have access to each other’s container. Adding them to the same app group creates a shared container which will be used for sharing data. We will do this by selecting the app from the list of Targets. Selecting Capabilities and then selecting/creating a group. Do the same for your extension.
The following image makes it easy to visualise the resulting architecture.
Our next job is to place the core data store in the shared container. Apple provides the developers with a class NSPersistentContainer which makes it easy to manage the core data stack. The class has a method defaultURLDirectory which we will be overriding to make the shared container the default location for the core data store.
We created a new class with NSPersistentContainer as it’s parent. And then we override the defaultURLDirectory method. We are almost done.
Next we change our code to use this custom class instead of NSPersistentContainer while setting up our stack (line 11).
We use the same code to set up the core data stack in the ShareViewController.swift (share sheet).
We are almost done. Notice that now we can get access to the view context in any function. Before we start celebrating there is one more thing to do. We are going to make our model available in the extension. To do this we simply select the model (.xcdatamodeld) and on the right pane select the extension under Target Membership.
Now our app and extension can both read and write to the same core data store and use the same model.