3

I want to access my CoreData from my Today Extension Widget to display some data. I already read that I have to create an app group and add this one to my App and my Widget. I already have done this, but now I'm not sure what to do next. I found an old tutorial but the methods used there aren't available or I'm not able to find them in AppDelegate. Can anybody help me please?

Philipp Rosengart
  • 713
  • 1
  • 8
  • 20

1 Answers1

3

You need to get the URL of the group container with containerURL(forSecurityApplicationGroupIdentifier: of FileManager passing the container identifier in both targets:

lazy var secureAppGroupPersistentStoreURL : URL = {
   let fileManager = FileManager.default
   let groupDirectory = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.mydomain.myapp")!
   return groupDirectory.appendingPathComponent("databaseName.sqlite")
}()
vadian
  • 274,689
  • 30
  • 353
  • 361
  • You need to add the appropriate capabilities in both app and today extension project : App Groups – CZ54 Feb 14 '17 at 09:22
  • Thanks but as I said I'm not able to understand the tutorial or the original post. I copied your code to my extension but I don't know how to work further to access my CoreData. – Philipp Rosengart Feb 15 '17 at 11:21
  • Actually if you pass `secureAppGroupPersistentStoreURL` as the store URL in the declaration of `persistentStoreCoordinator` you should be able to access the data from both the app and the extension. That's the only difference to a normal Core Data implementation. – vadian Feb 15 '17 at 13:19
  • Do you have any example? – Philipp Rosengart Feb 17 '17 at 15:50
  • Unfortunately no, I guess there is a tutorial on Ray Wenderlich's site. Of course you need to create the app group in the Developer Member Center and add the app group capability passing the app group identifier in both targets. – vadian Feb 17 '17 at 16:05