Swift - iOS10 - CoreData - FetchRequest in Today Widget always return 0 elements

768 views Asked by At

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.

1

There are 1 answers

1
Michal On BEST ANSWER

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Ƃ