Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch data from CoreData for iOS 14 widget

I want to display data fetched from Core Data in a widget. But @FetchRequest doesn’t work on widgets.

As I understand, we have to create an app group and make a shared persistent container.

What I want to know is how to read (fetch) data on widgets from that shared persistent container or simply, how to display data fetched from Core Data in widgets.

like image 269
umayanga Avatar asked Sep 17 '20 10:09

umayanga


Video Answer


1 Answers

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.

like image 103
pawello2222 Avatar answered Oct 24 '22 06:10

pawello2222