-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
233: Practice Exercise: Building an Offline Queue for Failed Network Requests
We've spent a lot of time talking about how to make network calls, but in the real world, the network is a liar. It tells you it's connected right until the moment a tunnel or a dead zone kills your request. If you just show a "Request Failed" alert every time, your users are going to hate you.
I prefer to build a "fire and forget" system for non-critical actions. If a user "likes" a post while walking into an elevator, we shouldn't block them with an error. Instead, we'll queue that request and sneak it through once the connection is stable again. Let's build a simple offline queue for a "Like" feature.
Defining a Pendable Request
First, we need a way to represent a request that hasn't happened yet. We can't just save a closure or a function call to disk; we need data. I'll create a PendingRequest struct that conforms to Codable so we can easily stash it in UserDefaults or a local file.
struct PendingRequest: Codable, Equatable {
let id: UUID
let postId: String
let action: ActionType
enum ActionType: String, Codable {
case like
case unlike
}
}
I'm using a UUID here because if a user likes and then quickly un-likes a post while offline, we need to ensure we process those in the exact order they happened.
Making the Queue Persistent
Now we need a manager to handle the list. I'm going to use a simple array backed by UserDefaults. In a massive production app, I'd probably use SQLite or Core Data, but for this pattern, the overhead of a database is overkill.
class OfflineQueueManager {
private let storageKey = "offline_requests_queue"
private var queue: [PendingRequest] = []
init() {
loadQueue()
}
func addRequest(_ request: PendingRequest) {
queue.append(request)
saveQueue()
}
private func saveQueue() {
if let encoded = try? JSONEncoder().encode(queue) {
UserDefaults.standard.set(encoded, forKey: storageKey)
}
}
private func loadQueue() {
if let data = UserDefaults.standard.data(forKey: storageKey),
let decoded = try? JSONDecoder().decode([PendingRequest].self, from: data) {
queue = decoded
}
}
}
Processing the Backlog (And my mistake)
Here is where I usually trip up when I'm rushing. My first instinct is to just loop through the queue and fire off every request as fast as possible. Let's look at how I initially wrote the processQueue method:
// DON'T DO THIS
func processQueue() async {
for request in queue {
await networkService.sendLike(postId: request.postId)
queue.removeAll { $0.id == request.id }
saveQueue()
}
}
The problem here is that I'm ignoring the result of the network call. If the user is still offline, this loop will run, "fail" every single request instantly, and then removeAll will wipe the entire queue. I've effectively deleted the user's pending actions without actually sending them. That's a nightmare for UX.
The fix is simple: only remove the request from the queue if the server actually acknowledges it. I'll change the loop to stop entirely the moment a request fails. If the first request in the queue fails, there's no point in trying the next ten; the network is still down.
func processQueue() async {
while !queue.isEmpty {
let request = queue[0]
do {
try await networkService.sendLike(postId: request.postId)
// Only remove if successful
queue.removeFirst()
saveQueue()
} catch {
print("Network still down, stopping queue processing.")
break // Stop the loop so we don't waste battery/data
}
}
}
Triggering the Retry
The last piece of the puzzle is knowing when to run this. You could run it every time the app foregrounds, or you could use a network reachability monitor. For this example, I usually hook it into the didBecomeActive notification or a simple timer. The key is that the OfflineQueueManager is a singleton or a long-lived instance that lives for the duration of the app session.
📋 Practical Task
Exercise: Implementing an Offline Message Sync for a Chat App
You are building a chat application where users can send messages. Currently, if the user hits "Send" while offline, the message simply disappears or shows an error, which is frustrating.
Your task is to implement an OfflineMessageQueue system. You must build the following:
- A
QueuedMessagestruct that stores therecipientId, themessageText, and atimestamp. It must beCodable. - An
OfflineMessageQueueclass that handles adding messages to a persistent list (usingUserDefaults). - A
syncMessages()function that processes the queue. This function must:- Process messages in the order they were sent (First-In-First-Out).
- Only remove a message from the queue if the mock network call succeeds.
- Stop processing the entire queue immediately if a network error occurs to prevent unnecessary API calls.
Requirement: Ensure that if the user sends three messages (A, B, and C) while offline, and only A and B succeed during the first sync attempt, message C remains in the queue for the next attempt.
There are no comments for now.