Share data between main App and Widget in SwiftUI for iOS 14

You can add the AppGroup capability for both your Widget and App (here is a very good explanation how to add it).


UserDefaults

Instead of

UserDefaults.standard

just use the shared UserDefaults for your AppGroup:

UserDefaults(suiteName: <your_app_group>)

Then you can read/write data like explained in this answer.

File Container

With the AppGroup entitlement you get access to the shared File Container:

let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: <your_app_group>)!

and access an url like this:

let someFileURL = containerURL.appendingPathComponent("SomeFile.txt")

Then you can use your shared File Container like explained in this answer:

CoreData

You can create a shared CoreData container as well:

let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
let description = NSPersistentStoreDescription(url: storeURL)

let container = NSPersistentContainer(name: "DataModel")
container.persistentStoreDescriptions = Share data between main App and Widget in SwiftUI for iOS 14
container.loadPersistentStores { ... }

Then you can use your shared CoreData Container like explained in this answer:


Here is a GitHub repository with different Widget examples including the App Group Widget.

Leave a Comment