Choosing from Coredata in ios app widget extension in ios 10

I am trying to extract objects from my coredata database of my main application and display them in widgets of my Extention applications. However, fetching always returns empty results from my database. Can help me. Swift 3, ios 10.

+5
source share
2 answers

I solved it. After creating the application group, I subclassed NSPersistentContainer and overrided the defaultDirectory () class method to return a directory of common application groups. Also override init (name: String, managedObjectModel model: NSManagedObjectModel). Then, in the coredata stack, you replace the persistentcontainer code with a template with a new instance of the created PersistentContainer class.

import UIKit import CoreData class PersistentContainer: NSPersistentContainer{ override class func defaultDirectoryURL() -> URL{ return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bundleId.SomeApp")! } override init(name: String, managedObjectModel model: NSManagedObjectModel) { super.init(name: name, managedObjectModel: model) } } 

Then, in CoreDataStack * code, wherever possible, either in Appdelegate or in its own file. Mine was in its own file called CoredataStack

 static var persistentContainer:PersistentContainer = { let container = PersistentContainer(name: "SomeApp", managedObjectModel: CoreDataStack.managedObjectModel) container.loadPersistentStores(completionHandler: { (storeDescription:NSPersistentStoreDescription, error:Error?) in if let error = error as NSError?{ fatalError("UnResolved error \(error), \(error.userInfo)") } }) return container }() 

Hope this helps

+5
source

Today Extension runs in another process from its containing application, so it does not exchange an isolated sandbox, UserDefaults or database. This is why you get an empty set when you try to retrieve the data stored in the container from the widget. If you want the containing application and widget to exchange data, you must add the "App Group" feature to your application through the iOS developer portal and provide it with the identifier string of the shared group. Then, when you instantiate the FileManager object for the database (or UserDefaults), you must use the initWithSuiteName method, passing the identifier of the common group.

+4
source

Source: https://habr.com/ru/post/1261085/


All Articles