Offline Queue
The offline queue buffers mutating requests (create, update, delete) when the device is offline and replays them in order when connectivity is restored.
Reads (list, get) are not queued — they need fresh data from the server.
Enable auto-flush on app launch. The queue uses NWPathMonitor to detect when the network becomes reachable.
// AppDelegate / App.swiftBunBaseClient.shared.offlineQueue.startMonitoring()Enqueue a mutation
Section titled “Enqueue a mutation”Enqueue a mutation when you detect the device is offline (or optimistically always, letting the SDK handle ordering):
// Explicit: enqueue when offlinedo { let post = try await posts.create(newPost)} catch BunBaseError.networkError { client.offlineQueue.enqueue( method: "POST", path: "/api/v1/posts", body: newPost // Encodable — serialised to JSON automatically )}Raw body data
Section titled “Raw body data”let bodyData = try JSONEncoder().encode(newPost)client.offlineQueue.enqueue(method: "POST", path: "/api/v1/posts", bodyData: bodyData)Delete / patch
Section titled “Delete / patch”client.offlineQueue.enqueue(method: "DELETE", path: "/api/v1/posts/\(post.id)")client.offlineQueue.enqueue(method: "PATCH", path: "/api/v1/posts/\(post.id)", body: patch)Flush results
Section titled “Flush results”Listen for per-item results after a flush:
client.offlineQueue.onFlushResult = { id, error in if let error { print("[\(id)] failed: \(error)") } else { print("[\(id)] replayed successfully") }}Flush behaviour by response:
| Server response | Result |
|---|---|
| 2xx | Item removed from queue, onFlushResult(id, nil) |
| 4xx | Item removed (permanent failure), onFlushResult(id, error) |
| 5xx / network | Item kept, onFlushResult(id, error) — will retry next flush |
Manual flush
Section titled “Manual flush”await client.offlineQueue.flush()Inspect the queue
Section titled “Inspect the queue”print(client.offlineQueue.pendingCount) // number of items waitingprint(client.offlineQueue.items) // [QueuedMutation] — FIFO orderClear the queue
Section titled “Clear the queue”Discards all pending mutations without replaying them. Useful if the user logs out or you decide the queued operations are no longer relevant.
client.offlineQueue.clear()Persistence
Section titled “Persistence”The queue is persisted to UserDefaults as JSON and survives app restarts. Tokens are refreshed automatically during flush — no extra setup needed.
Stop monitoring
Section titled “Stop monitoring”client.offlineQueue.stopMonitoring()