Usuario de SO por primera vez, muy emocionado de estar aquí.
Me encontré con un problema en el que intento acceder a mi modelo Core Data tanto en la aplicación principal como en la extensión de la aplicación, directorio de llamadas. He seguido muchas sugerencias en línea, sin embargo, ninguna parece funcionar.
Tengo el trabajo de extensión de directorio de llamadas y puedo recargar desde la aplicación principal. Imprimir en beginRequest lo confirma.
Luego creé un nuevo modelo de datos, CallerData con una entidad Caller con un solo número de atributo.
También registré un grupo de aplicaciones en Apple Developer y agregué el grupo en ambos objetivos. Todo es verde.
Luego obtuve mi contenedor persistente AppDelegate como:
lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "CallerData") let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.project.ios.core.data")!.appendingPathComponent("CallerData.sqlite") var defaultURL: URL? if let storeDescription = container.persistentStoreDescriptions.first, let url = storeDescription.url { defaultURL = FileManager.default.fileExists(atPath: url.path) ? url : nil } if defaultURL == nil { container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)] } container.loadPersistentStores(completionHandler: { [unowned container] (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } if let url = defaultURL, url.absoluteString != storeURL.absoluteString { let coordinator = container.persistentStoreCoordinator if let oldStore = coordinator.persistentStore(for: url) { do { try coordinator.migratePersistentStore(oldStore, to: storeURL, options: nil, withType: NSSQLiteStoreType) } catch { print(error.localizedDescription) } // delete old store let fileCoordinator = NSFileCoordinator(filePresenter: nil) fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil, byAccessor: { url in do { try FileManager.default.removeItem(at: url) } catch { print(error.localizedDescription) } }) } } }) return container }()Agregué Core Data a ambos objetivos y pude escribir y recuperar con éxito del almacén de datos en el controlador de vista de mi aplicación principal usando:
Save core data if let appDelegate = UIApplication.shared.delegate as? AppDelegate { let context = appDelegate.persistentContainer.viewContext guard let entityDescription = NSEntityDescription.entity(forEntityName: "Caller", in: context) else { return } let newValue = NSManagedObject(entity: entityDescription, insertInto: context) newValue.setValue(number, forKey: "number") do { try context.save() print("Saved \(number)") } catch { print("Saving error") } } Retrieve if let appDelegate = UIApplication.shared.delegate as? AppDelegate { let context = appDelegate.persistentContainer.viewContext let fetchRequest = NSFetchRequest<Caller>(entityName: "Caller") let numberSort = NSSortDescriptor(key:"number", ascending:true) fetchRequest.sortDescriptors = [numberSort] do { let results = try context.fetch(fetchRequest) for result in results { print("Block core data result \(result.number)") } } catch { print("Could not retrieve") } }Ahora, cuando intento obtener los datos de la extensión de mi aplicación, recibo muchos errores. A continuación se muestra el código de extensión y los errores.
lazy var persistentContainer: NSPersistentContainer = { let container = NSPersistentContainer(name: "CallerData") let storeURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.io.project.core.data")!.appendingPathComponent("CallerData.sqlite") var defaultURL: URL? if let storeDescription = container.persistentStoreDescriptions.first, let url = storeDescription.url { defaultURL = FileManager.default.fileExists(atPath: url.path) ? url : nil } if defaultURL == nil { container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: storeURL)] } container.loadPersistentStores(completionHandler: { [unowned container] (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } if let url = defaultURL, url.absoluteString != storeURL.absoluteString { let coordinator = container.persistentStoreCoordinator if let oldStore = coordinator.persistentStore(for: url) { do { try coordinator.migratePersistentStore(oldStore, to: storeURL, options: nil, withType: NSSQLiteStoreType) } catch { print(error.localizedDescription) } // delete old store let fileCoordinator = NSFileCoordinator(filePresenter: nil) fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil, byAccessor: { url in do { try FileManager.default.removeItem(at: url) } catch { print(error.localizedDescription) } }) } } }) return container }() let dataContext = persistentContainer.viewContext let fetchRequest = NSFetchRequest<Caller>(entityName: "Caller") let numberSort = NSSortDescriptor(key:"number", ascending:true) fetchRequest.sortDescriptors = [numberSort] do { let results = try dataContext.fetch(fetchRequest) for result in results { print("Block core data result from Call Directory Extension \(result.number)") } } catch { print("Could not retrieve") } [error] error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (256) CoreData: annotation: NSSQLiteErrorDomain : 14 CoreData: annotation: storeType: SQLite CoreData: annotation: configuration: PF_DEFAULT_CONFIGURATION_NAME CoreData: annotation: URL: file:///private/var/mobile/Containers/Shared/AppGroup/70930707-4B5E-46E8-9083-C0D446A5568D/CallerData.sqlite/ CoreData: annotation: options: CoreData: annotation: NSPersistentStoreRemoveUbiquitousMetadataOption : 1 The file “CallerData.sqlite” couldn't be opened.Cualquier ayuda es apreciada.
Gracias