Read CoreData in Today Widget in Swift or Objectiv

2019-10-04 02:22发布

问题:

I really need some simple code for me how to read CoreData in TodayWidget This steps I made:

  • Create new project with using CoreData (in AppDelegate)
  • Make an Entity in CoreData model and some Attributes like a name or date
  • in ViewController of App fill name and date with one record like "Martin" "10/11"

And Now I need to read this name in TodayViewController

Please really post here just some simple code from it, or how to edit AppDelegate for using appgroup ...

Thanks !

回答1:

Widgets have to be able to read the data in their code. In order to do this, you need to setup your CoreData files to be located in a 'group' folder in your project (You can set your CoreData Stack to relocate it's files in this folder). Then you'll configure a CoreData Stack in your extension that points to the same files. These group folders are folders that can be access across multiple targets/applications that have permissions for the group.

I will point out that it's far easier to use and sync NSUserDefaults across a widget and it's appropriate application than it is CoreData.

You'll want to read Apple's documentation about sharing extension data below:

Apple docs

Note the following section:

Sharing Data with Your Containing App

Even though an app extension bundle is nested within its containing app’s bundle, the running app extension and containing app have no direct access to each other’s containers.

BACKGROUND

To learn about containers, read About the iOS File System in File System Programming Guide.

You can, however, enable data sharing. For example, you might want to allow your app extension and its containing app to share a single large set of data, such as prerendered assets.