M-Swift All articles
Swift Architecture

The Red Dot Doesn't Lie — Except When It Does: Reconciling Notification Badges in Swift

M-Swift
The Red Dot Doesn't Lie — Except When It Does: Reconciling Notification Badges in Swift

Photo: Awu1996, CC BY-SA 3.0, via Wikimedia Commons

The badge on your app icon is the only piece of your product a user sees without opening anything. It's one integer, it's tiny, and it's almost always wrong.

Not dramatically wrong. Just off by one, or two, or stuck at "3" for a week after someone cleared their inbox on an iPad. And that's the problem: a badge that's slightly wrong is worse than no badge at all, because the user learns to ignore it. Once that happens, you've burned your cheapest notification channel for good.

So let's treat it honestly — as a distributed state problem with four writers and one renderer.

Four Writers, One Renderer

Your icon shows exactly one number. That number can be set by:

  1. The aps.badge key in a remote push payload.
  2. The badge property on a local notification's content.
  3. UNUserNotificationCenter.setBadgeCount(_:) called directly from your code.
  4. The system itself, when the user clears notifications out of Notification Center.

Four sources, none of which know about each other. Your server sends badge: 4 while the app has already read three of those items. A scheduled local reminder bumps the count to 5 while the backend still believes it's 2. The user swipes a notification away and iOS quietly adjusts — or doesn't, depending on how the payload was built.

Add a second device, a Focus mode, and a Notification Summary, and you've got a genuinely hard concurrency puzzle wearing a very small red hat.

The Rule That Fixes Most of This

The single highest-leverage change: make the server the only writer of absolute badge values, and make every value carry a revision.

A lot of teams send "badge": 3 from one endpoint and increment locally from another. That's two clocks. Pick one. The server computes the unread count, stamps it with a monotonically increasing revision, and pushes the absolute number. The client applies it only if the revision is newer than the last one it saw.

struct BadgeState: Codable {
    let unread: Int
    let revision: Int
}

final class BadgeCoordinator {
    private let center = UNUserNotificationCenter.current()
    private var lastApplied = -1

    func apply(_ state: BadgeState) async {
        guard state.revision > lastApplied else { return }
        lastApplied = state.revision
        do {
            try await center.setBadgeCount(max(0, state.unread))
        } catch {
            // A failed badge write is not worth a crash.
            print("Badge write failed: \(error)")
        }
    }
}

Store lastApplied in a shared App Group container so your widget and notification service extension read the same value. Otherwise your extension will happily clobber the main app's state during a background push at 3 a.m. and nobody will know until a support ticket shows up.

Stop Sending Relative Badges

If your APNs payload treats the badge as unread + 1, you've already lost. Pushes can arrive out of order, notifications collapse, and retries double-apply increments. Push absolute values. Always.

If a push is purely informational and shouldn't touch the count, omit the aps.badge key entirely — iOS leaves the current value alone, which is exactly what you want for a marketing message that has nothing to do with unread items. Sending badge: 0 there just to "clear" it is a common own-goal.

For local notifications, use UNMutableNotificationContent.badge sparingly. It's an absolute value too, which means it will fight your server if you let it. The clean pattern: local reminders set badge to the server's last known count, not to "current + 1".

Focus Modes Are Not the Enemy — Silence Is

A user in Focus mode still sees the badge. Focus silences delivery; it doesn't erase the number. That means your unread definition has to survive a person who hasn't glanced at their phone in six hours.

Two things worth checking:

A Reconciliation Pass You Can Ship This Week

You don't need a rewrite. You need one function that runs at four moments: app launch, return to foreground, after a push arrives, and after the user reads something.

func reconcileBadge(serverUnread: Int) async {
    let delivered = await UNUserNotificationCenter.current().deliveredNotifications()
    // Local fallback: if the server hasn't synced, at least don't lie upward.
    let floor = min(serverUnread, delivered.count + serverUnread)
    await BadgeCoordinator.shared.apply(
        BadgeState(unread: floor, revision: Int(Date().timeIntervalSince1970))
    )
}

That's deliberately boring, and boring is the point. The revision is time-based here because most teams won't have a server-side counter ready on day one — swap it for a real revision the moment you can.

Test the Drift, Not the Happy Path

Write down the scenarios that actually break badges, then check each one on a physical device rather than the simulator:

  1. Read an item on an iPad, then glance at the iPhone icon.
  2. Fire a push while the app is backgrounded, and another while it's foregrounded.
  3. Schedule a local reminder, then read the underlying item before it fires.
  4. Enable a Focus mode with a muted category and send three muted pushes.
  5. Force-quit the app, clear Notification Center, and relaunch.

If the number still matches after all five, you're in better shape than most of the App Store.

The Promise, Restated

A badge is a claim: there is something here worth your attention. Every mismatch erodes that claim a little. Treat the integer as shared state with a single owner, a revision, and a reconciliation pass — and your icon will stop lying. Which, for a red dot, is the entire job.

All Articles

Related Articles

Hard-Coded Hex and Rogue Padding: Auditing Your SwiftUI Design System Before the Redesign Lands

Hard-Coded Hex and Rogue Padding: Auditing Your SwiftUI Design System Before the Redesign Lands

Feature Flags Without the Baggage: A Swift-Native Rollout Layer

Feature Flags Without the Baggage: A Swift-Native Rollout Layer

Your Deep Link Works Until It Doesn’t: Seven SwiftUI Navigation Patterns to Audit Now

Your Deep Link Works Until It Doesn’t: Seven SwiftUI Navigation Patterns to Audit Now