SwiftData updates from CKSyncEngine (or any other background thread)

I'm currently managing two independent ModelContext instances in my app—one dedicated to CKSyncEngine and another for the Main/UI thread.

While this setup works to some extent, I'm encountering a couple of issues:

  1. UI Updates: When SwiftData is updated via CKSyncEngine, the UI doesn't automatically refresh. To address this, I've had to implement .refreshable() and write imperative Swift code to (re)fetch data. This approach feels counterintuitive since it prevents me from fully leveraging SwiftUI's declarative nature, such as using @Query and user must explicitly trigger refresh.

  2. Deletion Logic: If users delete data via the UI, I have to manage a different delete code path. Specifically, I need to ensure that the object is removed from the UI's ModelContext without triggering a deletion in CKSyncEngine's ModelContext. This dual-path deletion logic feels unnecessarily complex.

Also, I intend to later re-use CKSyncEngine part for Command Line tool app that will not have UI at all.

What is the correct way to manage SwiftData in a background process like CKSyncEngine while maintaining a seamless and declarative approach in SwiftUI?

Answered by DTS Engineer in 800400022

This topic seems to have been discussed in the following post:

Basically, there are bugs in SwiftData + SwiftUI, and the situation has been improved in Beta 6. If beta 6 doesn't help in your case, you can probably consider the workaround mentioned there.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

Accepted Answer

This topic seems to have been discussed in the following post:

Basically, there are bugs in SwiftData + SwiftUI, and the situation has been improved in Beta 6. If beta 6 doesn't help in your case, you can probably consider the workaround mentioned there.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

SwiftData updates from CKSyncEngine (or any other background thread)
 
 
Q