Entity is empty using Core data in Today extension - ios

I'd like to show photos in today extension using Core data. But, entity is empty. I don't any idea about that.
here is what I'm doing:
add app group in both of targets (app and extension)
check target membership in xcdatamodeld.
create CoreDataStack class for using Core data in today extension.
class CoreDataStack {
private init() {
NotificationCenter.default.addObserver(self,
selector: #selector(mainContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.managedObjectContext)
NotificationCenter.default.addObserver(self,
selector: #selector(bgContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.backgroundManagedObjectContext)
}
static let sharedStack = CoreDataStack()
var errorHandler: (Error) -> Void = {_ in }
#available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "name")
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container }()
#available(iOS 10.0, *)
lazy var viewContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
#available(iOS 10.0, *)
func performBackgroundTask(_ block: #escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
lazy var libraryDirectory: URL = {
let urls = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group...")
return urls!
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "name", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel:
self.managedObjectModel)
let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.kr....")
let urls = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.kr....")!.path
let url = directory!.appendingPathComponent("name.sqlite")
do {
try coordinator.addPersistentStore(ofType:
NSSQLiteStoreType,
configurationName: nil,
at: url,
options: nil)
} catch {
// Report any error we got.
NSLog("CoreData error \(error), \(error._userInfo)")
self.errorHandler(error)
}
return coordinator }()
lazy var backgroundManagedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.persistentStoreCoordinator = coordinator
return privateManagedObjectContext }()
#available(iOS 9.0, *)
lazy var managedObjectContext: NSManagedObjectContext = {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
return managedObjectContext }()
#objc func mainContextChanged(notification: NSNotification) {
backgroundManagedObjectContext.perform { [unowned self] in
self.backgroundManagedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
#objc func bgContextChanged(notification: NSNotification) {
managedObjectContext.perform{ [unowned self] in
self.managedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
func saveContext () {
if #available(iOS 10.0, *) {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.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)")
}
}
} else {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
add function in today extension view controller
func fetchData() {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Quotes")
if #available(iOS 10.0,*) {
let context = CoreDataStack.sharedStack.viewContext
do {
let results = try context.fetch(fetchRequest)
self.quotes = results as? [Quotes]
print("result = \(results)")
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return
}
}else {
//for ios 9.3~
let context = CoreDataStack.sharedStack.managedObjectContext
do {
let results = try context.fetch(fetchRequest)
self.quotes = results as? [Quotes]
print("result = \(results)")
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
return
}
}
for i in self.quotes! {
let image = UIImage(data: i.img! as Data, scale: 1.0)
self.quotesImgs.append(image!)
print("is that really image? \(image)")
print("app in for in sytax for coredata = \(self.quotesImgs)")
}
print("quotes \(self.quotes)")
}
print is result = [] / quotes Optional([])
What am I missing??

Related

How to delete all data from core data when persistentContainer is not in App delegate method in swift

I am new in Swift and I want to delete all data from core data. I have seen several examples but in all of them persistentContainer is in AppDelegate and in my case persistentContainer is not in AppDelegate. It is in a different class as shown below:
class CoreDataStack: NSObject {
static let sharedInstance = CoreDataStack()
private override init() {}
func applicationDocumentsDirectory() {
if let url = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).last {
print(url.absoluteString)
}
}
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Database")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
print(storeDescription)
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
In the AppDelegate method I am just calling it as
CoreDataStack.sharedInstance.applicationDocumentsDirectory()
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
CoreDataStack.sharedInstance.saveContext()
}
I tried this code but it does not work for me.
One of the solutions can be to use NSBatchDeleteRequest for all entities in the persistentContainer. You can add these methods to your CoreDataStack:
func deleteAllEntities() {
let entities = persistentContainer.managedObjectModel.entities
for entity in entities {
delete(entityName: entity.name!)
}
}
func delete(entityName: String) {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try persistentContainer.viewContext.execute(deleteRequest)
} catch let error as NSError {
debugPrint(error)
}
}
The whole code can be found here
Need to use NSBatchDeleteRequest for particular entity from persistentContainer
func deleteEntityData(entity : String) {
let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
do {
try CoreDataStack.sharedStack.mainContext.execute(deleteRequest)
CoreDataStack.sharedStack.saveMainContext()
} catch {
print ("There was an error")
}
}
I have detailed an answer in below link.
enter link description here
A more radical approach is to remove/recreate your persistent stores.
extension NSPersistentContainer {
func destroyPersistentStores() throws {
for store in persistentStoreCoordinator.persistentStores {
let type = NSPersistentStore.StoreType(rawValue: store.type)
try persistentStoreCoordinator.destroyPersistentStore(at: store.url!, type: type)
}
loadPersistentStores()
}
func loadPersistentStores() {
loadPersistentStores { _, error in
if let error { fatalError(error.localizedDescription) }
}
}
}
Usage: try container.destroyPersistentStores()
Source

CoreData iOS crash: _coordinator_you_never_successfully_opened_the_database_missing_directory

I receive a lot of crashes with in the stacktrace "_coordinator_you_never_successfully_opened_the_database_missing_directory" on the main thread. This is reported in Crashlytics as "This NSPersistentStoreCoordinator has no persistent stores (device locked). It cannot perform a save operation."
is "..._missing_directory" the same as description as Crashlytics is giving ?
what could be the cause ?
how should I solve this ?
#objc class PersistenceController : NSObject {
#objc static let shared = PersistenceController()
fileprivate var managedObjectModel: NSManagedObjectModel?
fileprivate var privateObjectContext: NSManagedObjectContext?
fileprivate var name: String = Bundle.main.bundleIdentifier!
fileprivate var storeLocation: NSURL?
#objc var managedObjectContext: NSManagedObjectContext?
#objc var databasePath: String {
if let storeLocation = self.storeLocation, let storeLocationPath = storeLocation.path {
return storeLocationPath
}
return "Could not find database path"
}
#objc func initializeCoreDataModel(name: String?) -> Bool {
if let safeName = name {
self.name = safeName
}
// Check if a context alreay exsist
if (self.managedObjectContext != nil) {
print("Context already exists, no need to create another")
return true
}
// Fetch the Core Data store
if let modelUrl = Bundle.main.url(forResource: self.name + "Datamodel", withExtension: "momd") {
// Create a model from the store
if let mom = NSManagedObjectModel(contentsOf: modelUrl) {
self.managedObjectModel = mom
// Create the object contexts
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: mom)
// Create MainQueue
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
// Create PrivateQueue
self.privateObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
self.privateObjectContext?.persistentStoreCoordinator = coordinator
// Set MainQueue's parent to PrivateQueue - Now we have Persistent Store Coord => Private => Main
self.managedObjectContext?.parent = self.privateObjectContext
// Create the Persistent Store
if let storeURL = self.storeURL() {
if let persistentStoreCoordinator = self.privateObjectContext?.persistentStoreCoordinator {
self.storeLocation = storeURL
let options: [String : Any] = [NSMigratePersistentStoresAutomaticallyOption: true,
NSPersistentStoreFileProtectionKey: FileProtectionType.none,
NSInferMappingModelAutomaticallyOption: true]
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.storeLocation as URL?, options: options)
return true
} catch {
CrashlyticsManager.shared.logCoreDataError(error: error as NSError)
}
}
} else {
print("Could not create document url")
}
} else {
print("Could not create model from core data store")
}
} else {
print("Could not find core data store")
}
return false
}
#objc func save() {
guard let privateContext = self.privateObjectContext, let managedContext = self.managedObjectContext else {
return
}
if (!privateContext.hasChanges && !managedContext.hasChanges) {
return
}
if !UIApplication.shared.isProtectedDataAvailable {
let userInfo = [NSLocalizedDescriptionKey: "isProtectedDataAvailable = false, cannot save()", "MainThread": Thread.isMainThread ? "true" : "false"]
let nsError = NSError(domain: "CoreData", code: 1001, userInfo: userInfo)
CrashlyticsManager.shared.logCoreDataError(error: nsError)
return
}
managedContext.performAndWait({
do {
try managedContext.save()
privateContext.perform({
do {
try privateContext.save()
} catch {
CrashlyticsManager.shared.logCoreDataError(error: error as NSError)
}
})
} catch {
CrashlyticsManager.shared.logCoreDataError(error: error as NSError)
}
})
}
#objc func detachLocalDatabase() {
save()
if let privateObjectContext = self.privateObjectContext {
privateObjectContext.reset()
}
if let context = self.privateObjectContext, let coordinator = context.persistentStoreCoordinator {
for store in coordinator.persistentStores {
do {
try coordinator.remove(store)
} catch {
print(error)
}
}
}
managedObjectModel = nil
managedObjectContext = nil
privateObjectContext = nil
}
#objc func attachLocalDatabase() -> Bool {
return initializeCoreDataModel(name: "PasNL")
}
static func clearDatabase() {
Coupon.deleteAll()
CardStatus.deleteAll()
Message.deleteAll()
Transaction.deleteAll()
Setting.deleteAll()
}
}
private extension PersistenceController {
func storeURL() -> NSURL? {
let applicationSupportDirectoryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]
let applicationPath = (applicationSupportDirectoryPath as NSString).appendingPathComponent(self.name)
let storePath = (applicationPath as NSString).appendingPathComponent("\(self.name).db")
let fileExists = FileManager.default.fileExists(atPath: storePath)
if !fileExists {
do {
try FileManager.default.createDirectory(atPath: applicationPath, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
return NSURL(fileURLWithPath: storePath)
}
}

core data implementation with non repeating code for big project

I have project where I use it from Deployment Target = 9.0, more than 10 Coredata entities, here I am trying to do a approach where model is not called from View, and having a single method that takes request to fetch and perform the task. This is my approach
AppDelegate.swift
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "CoreDB", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDB.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
}
return coordinator
}()
// MARK: - Core Data stack
#available(iOS 10.0, *)
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "CoreDB")
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.
*/
print("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
if #available(iOS 10.0, *) {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.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)")
}
}
}
else
{
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
CoredataHelper.swift
class func fetchCoreData(_ entity:String, key:String, order : Bool) -> NSArray {
//let context: NSManagedObjectContext = appDelegate.managedObjectContext
if #available(iOS 10.0, *) {
let persistantContainer = appDelegate.persistentContainer
let privateManagedObjectContext = persistantContainer.newBackgroundContext()
let managedObjectContext = persistantContainer.viewContext
var arr : NSArray = []
let request = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
let sortDescriptor = NSSortDescriptor(key: key, ascending: order)
request.sortDescriptors = [sortDescriptor]
do {
guard let searchResults : NSArray = try privateManagedObjectContext.fetch(request) as NSArray else {
print("Results were not of the expected structure")
}
arr = searchResults
} catch {
print("Error ocurred during execution: \(error)")
}
return arr
}
else
{
let moc = DbHelper .getContext()
let privateMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateMOC.parent = moc
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false;
let sortDescriptor = NSSortDescriptor(key: key, ascending: order)
fetchRequest.sortDescriptors = [sortDescriptor]
do {
let fetchDetails : NSArray = try moc.fetch(fetchRequest) as NSArray
return fetchDetails
} catch {
Crashlytics.sharedInstance().recordError(error)
return []
}
}
}
class func saveData(_ arr : NSArray) {
for i in 0 ..< arr.count
{
let dictionary = arr .object(at: i) as? NSDictionary
let entityDescription =
NSEntityDescription.entity(forEntityName: “1”,
in: managedObjectContext)
let req = NSFetchRequest<NSFetchRequestResult>(entityName: “1”)
req.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)]
let localId = "\(String(describing: dictionary!["createdAt"]!))"
let pred = NSPredicate(format:"createdAt == \(localId)")
req.predicate = pred
do {
let fetchedResults = try managedObjectContext.fetch(req) as! [1]
if fetchedResults.count > 0 {
}
else
{
let 1DataObj = 1(entity: entityDescription!,
insertInto: managedObjectContext)
print(dictionary)
1DataObj.createdAt = dictionary!["createdAt"]! as! NSNumber
}
}
catch {
print("Error getting values")
}
}
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch let nserror as NSError {
}
}
}
ViewController.swift
// Fetching
Array1 = CoredataHelper .fetchCoreData("1", key:"name", order: true)
Array2 = CoredataHelper .fetchCoreData("2", key:"hubId", order: true)
Array3 = CoredataHelper .fetchCoreData("3", key:"createdAt", order: true)
Array4 = CoredataHelper .fetchCoreData("4", key:"name", order: true)
Array5 = CoredataHelper .fetchCoreData("5", key:"name", order: false)
Array6 = CoredataHelper .fetchCoreData("6", key:"name", order: false)
//Save response from API
CoredataHelper .saveData(arr)
Is there any way I can improve this based on Best Practice I want to implement same for iOS 9 to latest iOS release.

How to use Core data in widget today extension?

I'd like to use core data in today extension.
I tried some ways down below.
create app group and target to both app and today extension!
create CoreDataStack class following this link
full code is here :
final class CoreDataStack {
static let sharedStack = CoreDataStack()
var errorHandler: (Error) -> Void = {_ in }
//#1
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "spark")
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container
}()
//#2
lazy var viewContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
//#3
// Optional
lazy var backgroundContext: NSManagedObjectContext = {
return self.persistentContainer.newBackgroundContext()
}()
//#4
func performForegroundTask(_ block: #escaping (NSManagedObjectContext) -> Void) {
self.viewContext.perform {
block(self.viewContext)
}
}
//#5
func performBackgroundTask(_ block: #escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
private init() {
//#1
NotificationCenter.default.addObserver(self,
selector: #selector(mainContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.managedObjectContext)
NotificationCenter.default.addObserver(self,
selector: #selector(bgContextChanged(notification:)),
name: .NSManagedObjectContextDidSave,
object: self.backgroundManagedObjectContext)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
//#2
lazy var libraryDirectory: NSURL = {
let urls = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask)
return urls[urls.count-1] as NSURL
}()
//#3
lazy var managedObjectModel: NSManagedObjectModel = {
let modelURL = Bundle.main.url(forResource: "spark", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
//#4
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel:
self.managedObjectModel)
let url = self.libraryDirectory.appendingPathComponent("spark.sqlite")
do {
try coordinator.addPersistentStore(ofType:
NSSQLiteStoreType,
configurationName: nil,
at: url,
options: [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
)
} catch {
// Report any error we got.
NSLog("CoreData error \(error), \(error._userInfo)")
self.errorHandler(error)
}
return coordinator
}()
//#5
lazy var backgroundManagedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
privateManagedObjectContext.persistentStoreCoordinator = coordinator
return privateManagedObjectContext
}()
//#6
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var mainManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
mainManagedObjectContext.persistentStoreCoordinator = coordinator
return mainManagedObjectContext
}()
//#7
#objc func mainContextChanged(notification: NSNotification) {
backgroundManagedObjectContext.perform { [unowned self] in
self.backgroundManagedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
#objc func bgContextChanged(notification: NSNotification) {
managedObjectContext.perform{ [unowned self] in
self.managedObjectContext.mergeChanges(fromContextDidSave: notification as Notification)
}
}
}
struct CoreDataServiceConsts {
static let applicationGroupIdentifier = "group.zz.zz.zz"//example
}
final class PersistentContainer: NSPersistentContainer {
internal override class func defaultDirectoryURL() -> URL {
var url = super.defaultDirectoryURL()
if let newURL =
FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: CoreDataServiceConsts.applicationGroupIdentifier) {
url = newURL
}
return url
}
I can get use core data in today extension! but, entity is empty.
And I tested code every thins is okay. there is no error (because I save some data for test, I perfectly work.)
I really don't know about this problem.
Is it problem about xcode?
You do not have to subclass NSPersistentContainer to be able to set a custom store directory.
class CoreDataStack {
public private(set) var persistentContainer: NSPersistentContainer
public init(withManagedObjectModelName momdName:String, sqliteStoreName storeName:String, storeBaseUrl baseUrl:URL?) {
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)")
}
persistentContainer = NSPersistentContainer(name: momdName, managedObjectModel: mom)
// If a base URL is given, use it. Else use persistent stores default
if let baseUrl = baseUrl {
var storeUrl = baseUrl.appendingPathComponent(momdName)
storeUrl = storeUrl.appendingPathExtension("sqlite")
let description = NSPersistentStoreDescription(url: storeUrl)
persistentContainer.persistentStoreDescriptions = [description]
}
persistentContainer.loadPersistentStores() { (storeDescription, error) in
if let error = error {
fatalError("Unresolved error \(error)")
}
}
}
// MARK: - ... save, get context and others ...
}
Instantiate it using your App Group directory:
guard let groupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: applicationGroupId) else {
fatalError("could not get shared app group directory.")
}
let modelName = "Model"
let storeName = "store"
let myStore = CoreDataStack(withManagedObjectModelName: modelName, sqliteStoreName: storeName, storeBaseUrl: groupURL)
Try creating a new "Cocoa Touch Framework" and place your xcdatamodeld file and custom managed object class there, so you can share them between the app and the extension.
Then subclass NSPersistentContainer.
class SparkPersistentContainer: NSPersistentContainer = {
override class func defaultDirectoryURL() -> URL {
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.example.your-app")!
init() {
let modelURL = Bundle(for: CustomManagedObject.self).url(forResource: "Spark", withExtension: "momd")!
let model = NSManagedObjectModel(contentsOf: modelURL)!
super.init(name: "Spark", managedObjectModel: model)
}
}

CoreData Stack for both iOS 9 and iOS 10 in Swift

I am trying to add Core Data to my existing project which supports iOS 9+.
I have added code generated by Xcode:
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "tempProjectForCoreData")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
After generating standard CoreData Stack in Xcode I found out that the new class of NSPersistentContainer is available from iOS 10 and as a result I get an error.
How should correct CoreData Stack should look like to support both iOS 9 and 10?
Here is the Core Data Stack that worked for me. I thought that in order to support iOS 10 I need to implement NSPersistentContainer class, but I found out that the older version with NSPersistentStoreCoordinator works as well.
You have to change name for your Model (coreDataTemplate) and project (SingleViewCoreData).
Swift 3:
// MARK: - CoreData Stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.cadiridris.coreDataTemplate" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "coreDataTemplate", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() 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.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() 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
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
Use the next Struct for ios 9 and 10
this is for context use the nex and replace ModelCoreData for your Model name of CoreData
Storage.share.context
import Foundation
import CoreData
/// NSPersistentStoreCoordinator extension
extension NSPersistentStoreCoordinator {
/// NSPersistentStoreCoordinator error types
public enum CoordinatorError: Error {
/// .momd file not found
case modelFileNotFound
/// NSManagedObjectModel creation fail
case modelCreationError
/// Gettings document directory fail
case storePathNotFound
}
/// Return NSPersistentStoreCoordinator object
static func coordinator(name: String) throws -> NSPersistentStoreCoordinator? {
guard let modelURL = Bundle.main.url(forResource: name, withExtension: "momd") else {
throw CoordinatorError.modelFileNotFound
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
throw CoordinatorError.modelCreationError
}
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
throw CoordinatorError.storePathNotFound
}
do {
let url = documents.appendingPathComponent("\(name).sqlite")
let options = [ NSMigratePersistentStoresAutomaticallyOption : true,
NSInferMappingModelAutomaticallyOption : true ]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
throw error
}
return coordinator
}
}
struct Storage {
static var shared = Storage()
#available(iOS 10.0, *)
private lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "ModelCoreData")
container.loadPersistentStores { (storeDescription, error) in
print("CoreData: Inited \(storeDescription)")
guard error == nil else {
print("CoreData: Unresolved error \(String(describing: error))")
return
}
}
return container
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
do {
return try NSPersistentStoreCoordinator.coordinator(name: "ModelCoreData")
} catch {
print("CoreData: Unresolved error \(error)")
}
return nil
}()
private lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: Public methods
enum SaveStatus {
case saved, rolledBack, hasNoChanges
}
var context: NSManagedObjectContext {
mutating get {
if #available(iOS 10.0, *) {
return persistentContainer.viewContext
} else {
return managedObjectContext
}
}
}
mutating func save() -> SaveStatus {
if context.hasChanges {
do {
try context.save()
return .saved
} catch {
context.rollback()
return .rolledBack
}
}
return .hasNoChanges
}
func deleteAllData(entity: String)
{
// let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = Storage.shared.context
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
fetchRequest.returnsObjectsAsFaults = false
do
{
let results = try managedContext.fetch(fetchRequest)
for managedObject in results
{
let managedObjectData:NSManagedObject = managedObject as! NSManagedObject
managedContext.delete(managedObjectData)
}
} catch let error as NSError {
print("Detele all data in \(entity) error : \(error) \(error.userInfo)")
}
}
}

Resources