

And with that, both the app and the extension will have access to the same data.įirst, we would need to activate the App Groups capability for both the app and the extension. In our case, we are going to store a JSON representation of our structure in a file inside the group's container. We have an Array of Friends, and we want both our app and our Today Extension to have access to that data.

Let's imagine we are building a Today Extension. The data stored inside a shared container is accessible to any target that belongs to that group. A shared container is created using App Groups.Īpp Groups were created to share containers between apps(and targets). Each target gets its own container, so everything is isolated, but there is also a way to create a shared container. We could, for example, share it by storing it on the UserDefaults, or by saving files to disk or using CoreData. Now let's have a more detailed look at each, we'll start with sharing data: That should give you more clarity on what we are going to do. Using this approach gives us reusability and lowers our maintenance problems (we don't have to deal with duplicated code/functionality). Then have both, the app and the extension, include the framework and get the same functionality.
#SWIFT SHARE IN IMESSAGE CODE#
To share code, we could move the code to a framework. If we keep our code in only one target, we won't be able to use it in the other.
#SWIFT SHARE IN IMESSAGE HOW TO#
The following is a summary of possible solutions on how to share data and code between targets: I'll show you one solution for each case, but remember there are more ways to solve this.

It also depends on what do we want to share, data or code. There are different ways to solve the information sharing between targets. We want to keep those benefits but also be able to share data when we want too. Having this separation has security benefits, a target can not interfere with another target's data. Because they are different targets they have different scopes, they can only access what is inside of their scope. A target could be an app, a framework, an extension, a test suite, etcetera. We know we can't access the app's files directly from our extension, that is because the app and the extension are different targets.
