I'm experiencing a significant UI freeze in my SwiftUI app that uses SwiftData with CloudKit sync. When users tap a button to present a sheet for the first time after app launch, the entire UI becomes unresponsive for 5-10 seconds. Subsequent sheet presentations work fine.
App Architecture
- Service layer: An @Observable class marked with @MainActor that orchestrates operations
- Persistence layer: A @ModelActor class that handles SwiftData operations
- SwiftUI views: Using @Environment to access the service layer
The structure looks like this:
@Observable
@MainActor
final class MyServices {
let persistence: DataPersistence
init(modelContainer: ModelContainer) {
self.persistence = DataPersistence(modelContainer: modelContainer)
}
func addItem(title: String) async {
// Creates and saves an item through persistence layer
}
}
@ModelActor
actor DataPersistence {
func saveItem(_ item: Item) async {
// Save to SwiftData
}
}
The app initializes the ModelContainer at the Scene level and passes it through the environment:
@main
struct MyApp: App {
let container = ModelContainer(for: Item.self)
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(container)
.environment(MyServices(modelContainer: container))
}
}
}
The Problem
When a user taps the "Add Item" button which presents a sheet:
Button("Add Item") {
showingAddSheet = true
}
.sheet(isPresented: $showingAddSheet) {
AddItemView(onAdd: { title in
await services.addItem(title: title)
})
}
The UI freezes completely for 5-10 seconds on first presentation. During this time:
- The button remains in pressed state
- No UI interactions work
- The app appears completely frozen
- After the freeze, the sheet opens and everything works normally
This only happens on the first sheet presentation after app launch. I suspect it's related to SwiftData's ModelContext initialization happening on the main thread despite using @ModelActor, but I'm not sure why this would happen given that ModelActor should handle background execution.
Environment
- iOS 18
- SwiftData with CloudKit sync enabled
- Xcode 16
- Swift 6
Has anyone experienced similar freezes with SwiftData and @ModelActor? Is there something wrong with how I'm structuring the initialization of these components? The documentation suggests @ModelActor should handle background operations automatically, but the freeze suggests otherwise.
Any insights would be greatly appreciated!