Refreshing fetch request when background process (share extension) updates it

Hi all,

I have a share extension which is adding data to a CoreData database via an instance of DataManager.

However when testing and outputting the content of fetch request using a button in the main app, I see that the fetch request does not have the new results after they are added by the share extension until I force close the app and reopen it.

I have tried refreshing the data using the refresh method defined below as well but without luck.

DataManager

import Foundation

class DataManager: ObservableObject {
    let container: NSPersistentContainer
    
    static var preview: DataManager = {
        
        let controller = DataManager(inMemory: false)
        return controller
    }()
    
    init(inMemory: Bool = false) {
        container = NSPersistentContainer(name: "DataModel")
        
        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: 
"/dev/null")    
        }
        else {
            let storeURL = URL.storeURL(for: "group.Highlightly", databaseName: "DataModel")
            let storeDescription = NSPersistentStoreDescription(url: storeURL)
            container.persistentStoreDescriptions = [storeDescription]
        }
        
        container.viewContext.automaticallyMergesChangesFromParent = true
        
        container.loadPersistentStores {description, error in
            if let error = error {
                print("Core Data Failed to load: \(error.localizedDescription)")
            }
        }
    }
}



public extension URL {

    static func storeURL(for appGroup: String, databaseName: String) -> URL {
        guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
            fatalError("Shared file container could not be created.")
        }

        return fileContainer.appendingPathComponent("\(databaseName).sqlite")
    }
}

extension DataManager {
    
    func saveDocument(title: String, content: String) {
        let document = Doc(context: container.viewContext)
        document.content = content
        document.title = title
        
        do {
            try container.viewContext.save()
            print("Document saved successfully")
            
        } catch {
            print("Failed to save document: \(error)")
            
            container.viewContext.rollback()
            
        }
    }
    
    func deleteDocument(document: Doc) {
        container.viewContext.delete(document)
        do {
            try container.viewContext.save()
            
            print("Document deleted successfully")
            
        } catch {
            print("Failed to delete document: \(error)")
            
            container.viewContext.rollback()
        }
    }
    func refresh() {
        print("refreshing all objects")
        container.viewContext.stalenessInterval = 0
        container.viewContext.refreshAllObjects()
        container.viewContext.stalenessInterval = -1
    }
}

DocumentView

import SwiftUI


struct DocuementsView: View {
    
    @Environment(\.managedObjectContext) var moc
    @EnvironmentObject
    private var dataManager: DataManager
    @FetchRequest(entity: Doc.entity(), sortDescriptors: []) private var documents: FetchedResults<Doc>
    
    var body: some View {
        VStack {
            Text("Imported Documents")
            VStack {
                List(documents) { document in
                    Text(document.title ?? "No title")
                        .swipeActions {
                            Button("Delete") {
                                dataManager.deleteDocument(document: document)
                            }.tint(.red)
                        }
                }.id(refreshID)
            }
            Button("Refresh") {
                dataManager.refresh()
                print(documents)
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ in
            dataManager.refresh()
        }
    }
}

Any help would be much appreciated as I am completely stuck at the moment. Thanks, Edward

Refreshing fetch request when background process (share extension) updates it
 
 
Q