How to answer
Offline mode works best as offline-first: the local database is the source of truth the UI reads from, and the network only feeds it. With SwiftData, views use @Query and render immediately; every user edit is written locally and appended to an outbox of pending changes in the same save, and a @ModelActor sync engine pushes that outbox in order, then pulls server changes since a sync token. Connectivity (NWPathMonitor as an async sequence) only decides when to try, never whether a write is allowed; conflicts are resolved by an explicit, per-entity policy.
Key points (walk-through)
- Requirements: read everything previously loaded, create/edit/delete offline, sync automatically when back online, no lost or duplicated writes, clear sync status, conflict handling
- Components: SwiftData
ModelContainer(entities +PendingChangeoutbox), repositories that write entity + outbox atomically,SyncEngine(@ModelActor),SyncAPI(Sendable), a connectivity watcher, and a small@MainActor @Observablesync-status model for the UI - Data flow (write): user edit → save entity +
PendingChangein onemodelContext.save()→ UI updates instantly via@Query→ when online, the engine sends changes oldest-first with the change ID asIdempotency-Key→ on success delete the outbox row and store the server version - Data flow (read): pull with
since: syncToken→ upsert by server ID (#Unique) → handle tombstones for deletions → save the new token - Conflicts: last-writer-wins by server timestamp (simple, loses data), field-level merge, server wins with the local copy kept as a draft, or a user prompt for documents; version numbers (
updatedAt/ revision) detect conflicts on the server - Trade-offs: a custom outbox + REST gives full control;
ModelConfiguration(cloudKitDatabase:)orCKSyncEnginegive Apple-managed sync for iCloud-only data; Core Data +NSPersistentCloudKitContaineris still common. Optimistic UI feels instant but must handle rejections - Failure modes: a change rejected permanently (mark failed, show "needs attention", don't block the queue forever), ordering dependencies (create-before-update; stop at the first transient failure), the app killed mid-sync (idempotency makes replays safe), clock skew (trust server timestamps)
- Background:
BGAppRefreshTaskfor opportunistic pulls; silent push to nudge a sync;URLSessionwithwaitsForConnectivityfor single requests - Privacy: the store holds user data, so use file protection, wipe on logout, and keep it out of shared App Group containers unless widgets need it
- Testing: Swift Testing with an in-memory
ModelConfiguration(isStoredInMemoryOnly: true)and a fakeSyncAPI: edits offline produce outbox rows, sync drains them in order, a failure stops the drain, a replay doesn't duplicate; Network Link Conditioner for manual tests
If they dig deeper
Don't pre-check reachability before requests (just try and handle errors); use the path monitor for UI ("Offline – changes will sync") and as a sync trigger. SwiftData history (fetchHistory with HistoryDescriptor) to find local changes instead of a hand-written outbox. Pass PersistentIdentifiers across actors, never model objects. Large binary data stored as files, referenced from the model. Partial sync / paging of the initial download.
Common pitfalls
Treating the network as the source of truth and caching on the side. Writing the entity and the outbox in separate saves (a crash loses the change). Retrying non-idempotent requests. Blocking all sync on one poison change. Using NotificationCenter + a global reachability singleton (the old pattern) instead of an async path stream. Undefined conflict behavior discovered in production.
How to use it
A persisted outbox, a @ModelActor that drains it in order, and a connectivity loop that triggers sync whenever the path becomes satisfied.
@Model final class PendingChange { // the outbox, stored next to the data
#Unique<PendingChange>([\.id])
var id: UUID // doubles as the server Idempotency-Key
var entityID: UUID
var kind: String // "create" | "update" | "delete"
var payload: Data // encoded DTO, not the @Model object
var createdAt: Date
var attempts = 0
init(entityID: UUID, kind: String, payload: Data) {
id = UUID(); self.entityID = entityID; self.kind = kind; self.payload = payload; createdAt = .now
}
}
protocol SyncAPI: Sendable { func push(changeID: UUID, kind: String, payload: Data) async throws }
@ModelActor
actor SyncEngine {
/// Push the outbox in order, then pull server changes. Stops at the first failure to keep order.
func sync(api: any SyncAPI) async {
let outbox = FetchDescriptor<PendingChange>(sortBy: [SortDescriptor(\.createdAt)])
for change in (try? modelContext.fetch(outbox)) ?? [] { // unreadable store: nothing to push this round
do {
try await api.push(changeID: change.id, kind: change.kind, payload: change.payload)
modelContext.delete(change)
} catch {
change.attempts += 1 // backoff and "needs attention" UI use this
break
}
}
try? modelContext.save() // if this fails, pushed changes replay next time; idempotency keys make that safe
// then pull: fetch changes since the stored token, merge with the conflict policy
}
}
func syncWhenOnline(_ engine: SyncEngine, api: any SyncAPI) async { // run from the app's .task
for await path in NWPathMonitor() where path.status == .satisfied {
await engine.sync(api: api)
}
}Start it once from the app: .task { await syncWhenOnline(engine, api: api) }, and also call engine.sync(api:) after each local edit, from pull-to-refresh, and from a BGAppRefreshTask.
Best practices
- Read from the local store; render immediately and refresh in the background
- Write the entity and its outbox entry in one save
- Make every mutation idempotent with a client-generated ID
- Sync in order, stop at transient failures, and park permanent failures
- Define conflict rules per entity before shipping
- Show sync status honestly (pending, syncing, failed), not just a spinner
Related concepts
- Offline-First, Data Synchronization, SwiftData (
@ModelActor,#Unique, history), Core Data,CKSyncEngine, Network Reachability, Idempotency, Background Tasks