How to answer
Offline persistence means the app keeps working without a network: it shows the last known data instantly, accepts edits, and reconciles later. The design is local-first: a local database (SwiftData, Core Data or SQLite) is the single source of truth the UI observes, the network only ever updates that store, and user edits go into the store plus an outbox of pending changes that a sync process drains when connectivity returns. This file is about the app-side design; the server-side reconciliation is in Data Synchronization.
Key points
- UI reads only from the local store (
@Query,@FetchRequest, an observed repository); network responses are written into the store, never straight into views - Writes are optimistic: save locally, enqueue a pending change in the same transaction, update the UI immediately
- The outbox is drained in order, with idempotency keys so retries can't duplicate, and exponential backoff with jitter
- Don't gate requests on reachability; just try. Use
NWPathMonitor(anAsyncSequence) to trigger a retry and to show an offline banner - Show sync status per item (pending, failed) and the age of cached data
If they dig deeper
Background sync uses BGAppRefreshTask / BGProcessingTask (or SwiftUI .backgroundTask), and URLSession background transfers for large uploads. Cache HTTP responses with URLCache for read-only content, but use a real database for anything the user edits or searches. The repository runs in an actor (@ModelActor for SwiftData) so imports and outbox work stay off the main actor. Actor reentrancy means two flush calls can interleave at await, which is another reason for idempotency keys (or a single-flight Task in the actor). Plan for storage limits and eviction of old cached data.
Common pitfalls
Treating offline as an error state instead of a normal one. Writing the change and the outbox entry in separate saves (a crash in between loses or duplicates work). Pre-checking reachability and skipping the request. Re-sending non-idempotent POSTs on retry. Hiding failed changes from the user. Storing secrets or tokens in the offline cache instead of the Keychain.
How to use it
import SwiftData
import Foundation
@Model final class PendingChange { // the "outbox"
var id: UUID
var noteID: UUID
var createdAt: Date
init(noteID: UUID) { id = UUID(); self.noteID = noteID; createdAt = .now }
}
@ModelActor
actor NoteRepository {
// Local write + outbox entry in ONE save: never lose a change
func save(text: String, noteID: UUID) throws {
let note = try modelContext.fetch(FetchDescriptor<Note>(
predicate: #Predicate { $0.id == noteID })).first ?? Note(id: noteID, text: "")
note.text = text
note.updatedAt = .now
modelContext.insert(note)
modelContext.insert(PendingChange(noteID: noteID))
try modelContext.save()
}
// Drain the outbox in order; stop at the first failure and retry later
func flush(to api: some NotesAPI) async throws {
let pending = try modelContext.fetch(
FetchDescriptor<PendingChange>(sortBy: [SortDescriptor(\.createdAt)]))
for change in pending {
let id = change.noteID
if let note = try modelContext.fetch(FetchDescriptor<Note>(
predicate: #Predicate { $0.id == id })).first {
try await api.upsert(NoteDTO(id: id, text: note.text), idempotencyKey: change.id)
}
modelContext.delete(change)
try modelContext.save()
}
}
}import Network
func syncWhenOnline(_ repository: NoteRepository, api: some NotesAPI) async {
for await path in NWPathMonitor() where path.status == .satisfied {
try? await repository.flush(to: api) // failed changes stay queued; retry on launch / foreground too
}
}Best practices
- Design the local schema first; the API shape should map onto it, not the other way round
- Queue every mutation in an outbox with an idempotency key and retry with backoff
- Show cached data immediately and indicate pending or failed sync in the UI
- Decide a conflict policy per entity before you ship
- Test offline with the Network Link Conditioner, airplane mode, and kill-and-relaunch mid-sync
Related concepts
- Data Synchronization, Core Data, SwiftData and SwiftUI, File Storage, caching, network reachability, background tasks