Skip to Content
Course content

233: Practice Exercise: Building an Offline Queue for Failed Network Requests

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 QueuedMessage struct that stores the recipientId, the messageText, and a timestamp. It must be Codable.
  • An OfflineMessageQueue class that handles adding messages to a persistent list (using UserDefaults).
  • 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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.