Fetch data from CoreData for iOS 14 widget

First you need to create an AppGroup which will be used to create a Core Data Persistent Container (here is a good explanation how to do it)

Then you need to create your own CoreData stack (an example can be found when you create a new empty project with CoreData enabled).

  • Accessing Core Data Stack in MVVM application

Assuming you have already created your Core Data model (here called DataModel), you now need to set the container url to your custom shared container location:

  • Share data between main App and Widget in SwiftUI for iOS 14
let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: <your_app_group>)!
let storeURL = containerURL.appendingPathComponent("DataModel.sqlite")
let description = NSPersistentStoreDescription(url: storeURL)

let container = NSPersistentContainer(name: "DataModel")
container.persistentStoreDescriptions = [description]
container.loadPersistentStores { ... }

Now you can get the managedObjectContext from your shared Persistent Container:

let moc = CoreDataStack.shared.managedObjectContext

and perform a fetch request with it (more information here)

let predicate = NSPredicate(format: "attribute1 == %@", "test")
let request = NSFetchRequest<SomeItem>(entityName: "SomeItem")
let result = try moc.fetch(request)

Apart from all the links above I recommend you also read this tutorial about Core Data:

  • Core Data with SwiftUI Tutorial: Getting Started

Here is a GitHub repository with different Widget examples including the Core Data Widget.