Reputation: 1
Im running into an issue where swiftdata works perfectly and saves my data if I comment out any lines that call performSync
but as soon as I try to call performSync()
, SwiftData fails to save any changes whatsoever. I pass in modelContext
into the custom class from the @Enviroment
operator from a view onAppear
. How do I fix this?
func performSync() async {
guard let notionService = notionService, isInitialized else { return }
// Set isSyncing on the main actor.
await MainActor.run {
isSyncing = true
}
do {
// Fetch the ideas on the main actor.
let ideas: [Idea] = try await MainActor.run {
let descriptor = FetchDescriptor<Idea>()
return try modelContext.fetch(descriptor)
}
try await notionService.syncIdeas(ideas)
// Save changes on the main actor.
await MainActor.run {
try? modelContext.save()
isSyncing = false
}
} catch {
print("Sync failed: \(error)")
await MainActor.run {
isSyncing = false
}
}
}
.onAppear{
if let paId = UserDefaults.standard.string(forKey: DefaultsKeys.parentPageId){
if !completedSetupSync{
authManager.setupSyncManager(parentPageId: paId, modelContext: modelContext)
completedSetupSync = true
}
}
}
I was expecting the code to not effect other container changes outside the class and also be able to save changes to the context itself.
Upvotes: 0
Views: 76