🍫 CocoaPatterns — iOS & Mac Development Since 2009 RSS
🍫 CocoaPatterns
Because someone has to write this stuff down
"We ship apps. Sometimes they even work."

Store App State on the App Icon Badge: A Production Architecture

4 billion bytes of iCloud storage and we're using a single integer visible on the home screen.

MO
Melissa Okonkwo
@mel_ios_eng · CocoaPatterns

Every iOS app has access to a persistent, always-visible integer that survives app termination, persists across reboots, and is writable without any special entitlements. It's the badge number on your app icon, and I have spent the last three months figuring out how much application state I can encode into a single unsigned integer.

The answer is: more than you'd think. Less than I need. We're in production.

"The badge number is the original NoSQL database. It's a document store with a cardinality of one."

The Encoding Scheme

We encode application state into badge numbers using a custom base-10 positional encoding system we call BadgeState™. The badge supports values from 0 to... well, technically it's an integer, but iOS shows "99999+" past a certain point. We treat this as a feature. "99999+" means the app is in an error state.

// BadgeState encoding. Format: AABBBCC
// AA  = Auth state (00=logged out, 01=logged in, 02=expired)
// BBB = Unread message count (000-999)
// CC  = Last sync status (00=ok, 01=failed, 42=???)
  • (void)encodeState:(AppState *)state { NSInteger badge = (state.authCode * 100000) + (state.unreadCount * 100) + (state.syncStatus); [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge]; }
⚠️ Known Issue

If the user manually clears the badge number, we lose all application state. We are calling this "notification-triggered state reset" and have filed it as a feature request for the notifications team to "coordinate with" us. They have not responded.

User Feedback

Our users have noticed that the badge number is "wrong" and "confusing" and "shows 10847 when I have no messages." We've addressed this in the FAQ: "The badge number represents your personalized app health score. Higher is better." This has not reduced the feedback volume.

3 Comments — Powered by Disqus
TK
t_kim_ios · 6 weeks ago
"Notification-triggered state reset" is the most courageous reframing I've seen in engineering.
MO
mel_ios_engAuthor · 6 weeks ago
The badge hit 99999+ in production last Tuesday. We told users it meant "Premium Mode activated." Nobody pushed back.
BK
bradkow_ios · 6 weeks ago
This is the most creative use of UIApplication I have ever seen. I am afraid to ask questions.