I am in this scenario:

  1. My app extension (share extension) insert a new entry using CoreData and the CoreData's SQLite file stored in the app group's shared directory.
  2. While switching back to the main app, the main context does not update.

I used CoreDataStack.shared.mainContext.reset() but it does not work.

My core stack core (both of my main app and the app extension use this code):

import CoreData

public class CoreDataStack {

    let appID = "xxx"
    let modelFileName = "xxx"
    let defaultAppGroupID = "xxx"

    public static let shared = CoreDataManager()

    public var mainContext: NSManagedObjectContext {
        return mainPersistentContainer.viewContext
    }
    // MARK: - Core Data stack

    lazy var managedObjectModel: NSManagedObjectModel = {
        let bundle = Bundle(for: type(of: self))
        let momdURL = bundle.url(forResource: modelFileName, withExtension: "momd")!
        return NSManagedObjectModel(contentsOf: momdURL)!
    }()

    lazy var mainPersistentContainer: NSPersistentContainer = {
        let container = NSPersistentContainer(name: modelFileName, managedObjectModel: managedObjectModel)

        container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: defaultAppGroupID)!.appendingPathComponent("\(modelFileName).sqlite"))]

        container.loadPersistentStores(completionHandler: { (_, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        return container
    }()

    public func saveMainContext() {
        let context = mainPersistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }

    fileprivate func applicationDocumentsDirectory() -> URL {
        let fileManager = FileManager.default

        if let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.io.wildcat.InfoFlow") {
            return url
        } else {
            let urls = fileManager.urls(for: .documentDirectory, in: .userDomainMask)
            return urls[0]
        }
    }
}

0 Answers