Did you tried to publish change in the main thread? (DispatchQueue.main.async { // changes here..//}). Actually I have the same problem here. I need to update the list in the App after that new items has been added via Shortcut.
Post
Replies
Boosts
Views
Activity
Short Answer: It is a bug. Just run (command + R) your app then stop it. Then talk to your Siri. You will see the new Item is added to your list. I think debugger stops core data to be updated from external events.
Long Answer: I also tried many different approaches in the web and nothing worked. But here is the simplest code that I could add item to my list via Siri.
Simply setup your PersistenceController
public struct PersistenceController {
public static let shared = PersistenceController()
public let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "YourApp.")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
else {
let storeURL = AppGroup.coredata.containerURL.appendingPathComponent("YourApp.sqlite")
let description = NSPersistentStoreDescription(url: storeURL)
container.persistentStoreDescriptions = [description]
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
public func save() {
let context = container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Show some error here
print("Error saving data...")
}
}
}
}
Define your fetchRequest in your view
// your listView
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \item.name, ascending: true)],
animation: .default)
var items: FetchedResults<Items>
// use items in your list
List {
ForEach(items, id: \.self) { item in
NavigationLink {
ItemDetailsView(selectedItem: item)
} label: {
ListItemRow(item: item) // <- item should be @ObservedObject
}
}
}
Define your item as @ObservedObject in ListItemRow
As simple as that!