Fetch data from CoreData for iOS 14 widget

浪尽此生 提交于 2020-12-22 06:26:20

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/63936425/fetch-data-from-coredata-for-ios-14-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!