Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetching from Coredata in ios app widget extension in ios 10

Im trying to fetch entities from my coredata database of my main app and display them in my apps widget Extention. However the fetch always returns an empty results from my database. Can ayone help me out. Swift 3, ios 10.

like image 445
Shadrach Mensah Avatar asked Dec 10 '16 12:12

Shadrach Mensah


1 Answers

I solved it. After creating the App Group, I created a subclass of NSPersistentContainer and override the class method defaultDirectory() to return the shared app group directory. Also override the init(name: String, managedObjectModel model: NSManagedObjectModel). Then in the coredata stack you replace the boilerplate persistentcontainer code with a new instance of the PersistentContainer class created.

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 the CoreDataStack Code *wherever that maybe, either in the Appdelegate or or its own file. Mine was in its own file named 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 out

like image 119
Shadrach Mensah Avatar answered Oct 05 '22 04:10

Shadrach Mensah