Search code examples
core-dataswiftuiappdelegateuiscenedelegate

Is it possible to create a Fetch Request for core data entities within Scene Delegate for SwiftUI


I'm trying to keep synchronize my core data entities with a webservice i'm using. The issue is the web service updates the items every day, so I'm trying to create a fetch request to compare the cached items with the remote items and update the cached items if there are any changes, deletions, or additions.

Ideally I'd like to have this operation completed before the user enters the app. So i'm trying to create a fetch request inside my Scene Delegate.

The logic is this: On app load, I parse the items from my json webservice. At the same time I create a fetch request for the existing local core data entities, compare the local items with the remote items and update the cached items if needed.

Is this possible? Any suggestions or advice on how and when to do this would be greatly appreciated!


Solution

  • it's not that complex. You are already have a context in a sceneDelegate when creating a View. Just perform fetch.

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        let fetchRequest: NSFetchRequest<YourEntity> = YourEntity.fetchRequest()
        fetchRequest.sortDescriptors = []
        //fetchRequest.predicate = //some filters
        let result = try? context.fetch(fetchRequest)//it always returns an array but it may be empty. Fetch may throw if disc is unavailable or some other reasons
        //do what you need
        let contentView = ContentView().environment(\.managedObjectContext, context)
    

    in general, you can store an UUID as an object version. Every time you modify the object in backend, you can update the version with new UUID. Therefore, you need only to check versions - if it differs, you need to update object. But it only in case user can't modify the object offline. If he can, there must be some complex logic for collision solving.