iosswiftswift-extensions

Shared file between app extension and main app


I need your help to figure out how to make my .json file accessible by both the main app and the app extension. I have an extension that, when the post button is pressed, writes some data in a .json file. But when I try to read the file in the main app, the main app reads a blank file in a wrong path, in fact the app reads in this position: https://i.sstatic.net/idP3d.png and the extension writes a file in this path: https://i.sstatic.net/v8yhr.png. I have tried to include the file in the bundle resources and set the membership of the file for both the apps, but nothing worked. To get the path of the files I use this method:

let file = Bundle.main.url(forResource: "commonfile", withExtension: "json")

You help is really appreciated


Solution

  • You can use App Group feature to share file between apps/extensions:

    1. Activate App Group for both targets: Project Settings -> Capabilities -> Activate App Group -> add new App Groups ID (usually using group.$(YOUR_APP_BUNDLE_ID))
    2. Files/Folders located in this url will be access by both targets: appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "YOUR_GROUP_BUNDLE_ID")

    Hope this helps.