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)
}
}
Related
I have developed a framework that has its own database based on Core Data. The problem is that sometimes after an update the data changes but does not persist. And when closing and opening the application the data remains the old ones. The Core Data stack to initialize it and do the save operations is as follows:
import CoreData
// MARK: - TypeAliases
typealias BatchTask=(_ workerContext: NSManagedObjectContext) -> ()
// MARK: - Notifications
enum CoreDataStackNotifications : String{
case ImportingTaskDidFinish = "ImportingTaskDidFinish"
}
// MARK: - Main
internal struct CoreDataStack {
// MARK: - Properties
private let model : NSManagedObjectModel
private let coordinator : NSPersistentStoreCoordinator
private let modelURL : URL
private let dbURL : URL
private let persistingContext : NSManagedObjectContext
private let backgroundContext : NSManagedObjectContext
public let context : NSManagedObjectContext
// MARK: - Initializers
public init?(modelName: String){
guard let modelURL = Bundle(identifier: "com.my.framework")!.url(forResource: modelName, withExtension: "momd") else {
MyLogger.printLog("Unable to find \(modelName)in the main bundle")
return nil}
self.modelURL = modelURL
// Try to create the model from the URL
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
MyLogger.printLog("unable to create a model from \(modelURL)")
return nil
}
self.model = model
// Create the store coordinator
coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
// Create a persistingContext (private queue) and a child one (main queue)
// create a context and add connect it to the coordinator
persistingContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
persistingContext.name = "Persisting"
persistingContext.persistentStoreCoordinator = coordinator
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = persistingContext
context.name = "Main"
// Create a background context child of main context
backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
backgroundContext.parent = context
backgroundContext.name = "Background"
// Add a SQLite store located in the documents folder
let fm = FileManager.default
guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else {
MyLogger.printLog("Unable to reach the documents folder")
return nil
}
self.dbURL = docUrl.appendingPathComponent("modelMyFrameworkSDK.sqlite")
do {
try addStoreTo(coordinator: coordinator,
storeType: NSSQLiteStoreType,
configuration: nil,
storeURL: NSURL(fileURLWithPath: dbURL.absoluteString),
options: nil)
} catch {
MyLogger.printLog("unable to add store at \(dbURL)")
}
}
// MARK: - Utils
func addStoreTo(coordinator coord : NSPersistentStoreCoordinator,
storeType: String,
configuration: String?,
storeURL: NSURL,
options : [NSObject : AnyObject]?) throws{
try coord.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil)
}
}
// MARK: - Removing data
extension CoreDataStack {
func dropAllData() throws{
// delete all the objects in the db. This won't delete the files, it will
// just leave empty tables.
try coordinator.destroyPersistentStore(at: dbURL, ofType:NSSQLiteStoreType , options: nil)
try addStoreTo(coordinator: self.coordinator, storeType: NSSQLiteStoreType, configuration: nil, storeURL: NSURL(fileURLWithPath: dbURL.absoluteString), options: nil)
}
}
// MARK: - Batch processing in the background
extension CoreDataStack{
func performBackgroundBatchOperation(batch: #escaping BatchTask){
backgroundContext.perform() {
batch(self.backgroundContext)
// Save it to the parent context, so normal saving
// can work
do{
try self.backgroundContext.save()
}catch{
fatalError("Error while saving backgroundContext: \(error)")
}
}
}
}
// MARK: - Heavy processing in the background.
// Use this if importing a gazillion objects.
extension CoreDataStack {
func performBackgroundImportingBatchOperation(batch: #escaping BatchTask) {
// Create temp coordinator
let tmpCoord = NSPersistentStoreCoordinator(managedObjectModel: self.model)
do{
try addStoreTo(coordinator: tmpCoord, storeType: NSSQLiteStoreType, configuration: nil, storeURL: NSURL(fileURLWithPath: dbURL.absoluteString), options: nil)
}catch{
fatalError("Error adding a SQLite Store: \(error)")
}
// Create temp context
let moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
moc.name = "Importer"
moc.persistentStoreCoordinator = tmpCoord
// Run the batch task, save the contents of the moc & notify
moc.perform() {
batch(moc)
do {
try moc.save()
}catch{
fatalError("Error saving importer moc: \(moc)")
}
let nc = NotificationCenter.default
let n = Notification(name:Notification.Name(rawValue: CoreDataStackNotifications.ImportingTaskDidFinish.rawValue),
object: nil)
nc.post(n)
}
}
}
// MARK: - Save
extension CoreDataStack {
public func save() {
// We call this synchronously, but it's a very fast
// operation (it doesn't hit the disk). We need to know
// when it ends so we can call the next save (on the persisting
// context). This last one might take some time and is done
// in a background queue
context.performAndWait(){
if self.context.hasChanges{
do{
try self.context.save()
}catch{
fatalError("Error while saving main context: \(error)")
}
}
if self.persistingContext.hasChanges{
// now we save in the background
self.persistingContext.perform(){
do{
try self.persistingContext.save()
}catch{
fatalError("Error while saving persisting context: \(error)")
}
}
}
if self.backgroundContext.hasChanges {
self.backgroundContext.perform(){
do{
try self.backgroundContext.save()
}catch{
fatalError("Error while saving persisting context: \(error)")
}
}
}
}
}
func autoSave(delayInSeconds : Int){
if delayInSeconds > 0 {
MyLogger.printLog("Autosaving")
save()
DispatchQueue.main.asyncAfter(deadline: .now() + Double(delayInSeconds)) {
self.autoSave(delayInSeconds: delayInSeconds)
}
}
}
}
The creation of the objects is as shown below:
public static func myObject(withData1 data1: String, data2: Bool, context: NSManagedObjectContext) -> MyObject {
let myObject = NSEntityDescription.insertNewObject(forEntityName: MyObject.entityName(), into: context) as! MyObject
myObject.data1 = data1
myObject.data2 = data2
myObject.creationDate = Date()
myObject.modificationDate = Date()
return myObject
}
And the update of the objects is as you can see below:
public func update(withJSONObject JSONObject: [String: Any]) {
guard let data1 = JSONObject["data1"] as? String else { return }
guard let data2 = JSONObject["data2"] as? Bool else { return }
self.data1 = data1
self.data2 = data2
self.modificationDate = Date()
}
The creation and updating of the objects is done in the return callback of a call to the server.
I have tried executing these actions in the main thread in case that was the problem. And I tried to use context.perform {}
context.perform {
object.update(withJSONObject: json)
coreDataStack.save()
}
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)
}
}
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??
I try to use CoreData in my Main Application and I want to access it via an Today Extension and later in my WatchApp.
I added a new target for my Today Widget - than activated AppGroups for both targets. Of course the same appGroup.
Then I builded an "SharedCode" Framework. To share helper classes and my CoreDataStack class in both, my Main and Today application.
I builded the CoreDataStack mentioned in this Blogpost: https://swifting.io/blog/2016/09/25/25-core-data-in-ios10-nspersistentcontainer/
Also I added this code tho change the directory:
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
}
}
This is my CoreDataStack Helper class:
struct CoreDataServiceConsts {
static let applicationGroupIdentifier = "nnnnnnnnn.group.is.xnd.xyz"
static let modelName = "Weight"
}
public class CoreDataStack {
public static let shared = CoreDataStack()
public var errorHandler: (Error) -> Void = {_ in }
//#1
public lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: CoreDataServiceConsts.modelName)
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container
}()
//#2
public lazy var viewContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
//#3
// Optional
public lazy var backgroundContext: NSManagedObjectContext = {
return self.persistentContainer.newBackgroundContext()
}()
//#4
public func performForegroundTask(_ block: #escaping (NSManagedObjectContext) -> Void) {
self.viewContext.perform {
block(self.viewContext)
}
}
//#5
public func performBackgroundTask(_ block: #escaping (NSManagedObjectContext) -> Void) {
self.persistentContainer.performBackgroundTask(block)
}
public func saveContext () {
guard viewContext.hasChanges else { return }
do {
try viewContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}
}
}
And I builded a subclass for NSPersistentContainer:
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
}
}
In my Main Application I use NSFetchedResultController - adding and getting Entitys is working perfectly fine :)
Now I want to read from CoreData - I use a FetchRequest:
func fetchWeights() {
let fetchRequest: NSFetchRequest<Measure> = Measure.fetchRequest()
let dateSort = NSSortDescriptor(key: #keyPath(Measure.date), ascending: false)
fetchRequest.sortDescriptors = [dateSort]
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try CoreDataStack.shared.viewContext.fetch(fetchRequest)
if results.count > 0 {
// There are found Weigts
print("weights FOUND: \(results.count)")
} else {
// Nil Weights found
print("NO weights: \(results.count)")
}
} catch let error as NSError {
print("Fetch error: \(error) description: \(error.userInfo)")
}
}
No the fetch request always return zero objects.
But there are entities in my CoreData - there are showing in my Main App.
Any ideas?
I have no idea what Im doing wrong..
Thanks for your help.
You have defined a PersistentContainer subclass to override
defaultDirectoryURL, but your CoreDataStack is still using the build in NSPersistentContainer type for your lazy container.
This should do the trick:
public class CoreDataStack {
public static let shared = CoreDataStack()
public var errorHandler: (Error) -> Void = {_ in }
//#1
public lazy var persistentContainer: PersistentContainer = {
let container = PersistentContainer(name: CoreDataServiceConsts.modelName)
container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
if let error = error {
NSLog("CoreData error \(error), \(error._userInfo)")
self?.errorHandler(error)
}
})
return container
}()
Cheers
MichaĆ
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)")
}
}
}