2

I want to share Core Data with the Widget. I guess I'll need to create App Group (I know how to do this). But how do I then share the Core Data database with the Widget?

If I wanna use Core Data in my app, I always just simply create a new Xcode project and check "Use Core Data", and I get this code (Persistence.swift - below), which hooks me up to a database.

How can I modify it, so that this Core Data database is shared with the Widget?

Persistence.swift

import CoreData

struct PersistenceController {
    static let shared = PersistenceController()

    static var preview: PersistenceController = {
        let result = PersistenceController(inMemory: true)
        let viewContext = result.container.viewContext
        for _ in 0..<10 {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()
        }
        do {
            try viewContext.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nsError = error as NSError
            fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
        }
        return result
    }()

    let container: NSPersistentContainer

    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "MyAppName")
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true
    }
}

1 Answer 1

5

In the PersistenceController class first add a property to get the URL of the App Group

var containerURL: URL {
   return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myappname")!
}

then set the URL in the store descriptions of the persistent container

init(inMemory: Bool = false) {
    container = NSPersistentContainer(name: "MyAppName")
    if inMemory {
        container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
    } else {
        let storeURL = containerURL.appendingPathComponent("MyAppName.sqlite")
        container.persistentStoreDescriptions.first!.url = storeURL
    }
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in ...

Replace the string literals with your actual data.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! So after adding containerURL property, I have to replace the lines container = NSPersistentContainer(name: "MyAppName") and if inMemory {...} with let storeURL = containerURL.appendingPathComponent("MyAppName.sqlite") let description = NSPersistentStoreDescription(url: storeURL) container = NSPersistentContainer(name: "MyAppName") container.persistentStoreDescriptions = [description] Correct?
It gave me error😕: 'self' used before all stored properties are initialized imgur.com/a/11fNRcj
Please see the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.