0

If you need to share your core data with app extensions it can be useful to store the container in a shared group.

lewis
  • 2,936
  • 2
  • 37
  • 72

1 Answers1

0

You have to get a description of the container and then set the URL:

let momdName = "MyModel"

guard let modelURL = Bundle(for: type(of: self)).url(forResource: momdName, withExtension:"momd") else {
    fatalError("Error loading model from bundle")
}

guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
    fatalError("Error initializing mom from: \(modelURL)")
}

guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my-group")?.appendingPathComponent("My.sqlite") else {
    fatalError("Cannot get shared group URL")
}

let container = NSPersistentCloudKitContainer(name: momdName, managedObjectModel: mom)

guard let description = container.persistentStoreDescriptions.first else {
    fatalError("###\(#function): Failed to retrieve a persistent store description.")
}

description.url = containerURL

container.loadPersistentStores() { (storeDescription, error) in
    if let error = error as NSError? {
        // ...
    }
}
lewis
  • 2,936
  • 2
  • 37
  • 72