从CoreData for iOS 14小部件获取数据 [英] Fetch data from CoreData for iOS 14 widget

查看:385
本文介绍了从CoreData for iOS 14小部件获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在小部件中显示从Core Data获取的数据。但是 @FetchRequest 在小部件上不起作用。

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.

推荐答案

首先,您需要创建一个AppGroup,该AppGroup将用于创建Core Data Persistent Container(此处是如何执行此操作的很好的解释)

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)

然后,您需要创建自己的CoreData堆栈(在启用了CoreData的情况下创建新的空项目时,可以找到一个示例)。

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

假设您已经创建了核心数据模型(此处称为 DataModel ),您现在需要将容器网址设置为您的自定义共享容器位置:

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 { ... }

现在您可以从共享的持久容器中获得 managedObjectContext

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)

除了上面的所有链接之外,我建议您还阅读有关Core Data的本教程:

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

  • Core Data with SwiftUI Tutorial: Getting Started

这篇关于从CoreData for iOS 14小部件获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆