Hello
Is there a way to share data stored in CloudKit and CoreData between iOS and watchOS in SwiftUI? I am using the same CoreData file both, and I am using the same PersistenceController file both, and I am using the same CloudKit container for both. I tried adding the App Groups capability to all the targets, but it is not working. (I already enabled iCloud capability, Push notification capability and background Modes capability for both iOS and WatchOS)
PersistenceController:
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentCloudKitContainer
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "Test7")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy
}
}
View:
struct ContentView: View {
@FetchRequest(
entity: Item.entity(),
sortDescriptors: []
) var items: FetchedResults<Item>
@Environment(\.managedObjectContext) private var context
var body: some View {
NavigationView{
List {
ForEach(items) { item in
Text("Item at \(item.date!)")
}
.onDelete(perform: deleteItems)
}
.toolbar {
Button {
addItem()
} label: {
Image(systemName: "plus")
}
}
}
}
private func addItem() {
withAnimation {
let newItem = Item(context: context)
newItem.date = Date()
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(context.delete)
do {
try context.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
Thank you