1 minute read

Building a habit tracker app with UIKit and UserDefaults

A habit tracker can look simple: one table, a few buttons, and a streak counter. As a developer in Atyrau, Kazakhstan, I wanted to understand what changes when the screen must remain useful after the app closes. Using Swift, Xcode, and UIKit, I built a small iOS app that stores habits, records daily completions, and restores its state after a relaunch.

The goal was not to imitate every feature in a commercial product. It was to make the complete loop obvious: add a habit, mark it done for today, and see the result survive. That narrow scope kept the data model, interface, and persistence layer close together, helping me learn how a UIKit app moves between user actions, view controllers, and durable local storage.

The project also needed language that felt at home in Australia. Labels such as “no worries” for an error and “arvo” for an afternoon reminder can create a relaxed tone, but only if the underlying behaviour is reliable. A friendly interface cannot repair a failed write or a date calculated in the wrong time zone, so those details received the same attention as the visual design.

Start with a small habit model

Start with a record that can describe one habit and nothing else. An Identifiable, Codable struct can hold a UUID, title, creation date, and a set of completed days. The UUID keeps list identity stable when titles change, while Codable provides a clean bridge between the Swift model and UserDefaults.

Dates deserve more care than a Boolean called isCompleted. A multi-day streak needs a history rather than one flag. Storing normalised completion dates makes it possible to calculate the current streak, reset yesterday’s state, and show a weekly summary without guessing which day the user meant.

Local examples also shape the data. A Melbourne user might connect a habit with checking the weather before leaving home, while someone in Sydney could track a walk along the Bondi-to-Coogee coastal path. Those routines are ordinary, but they need dates interpreted in the device’s current time zone and calendar.

Persist habits with UserDefaults

UserDefaults is a key-value store for preferences and compact application state. It is convenient for a handful of records, but it is not a database, secure vault, or unbounded history log. For this tracker, its simplicity is an advantage: the collection remains small enough to encode and load without introducing a database stack.

Encoding gives the stored data a clear boundary. I convert the [Habit] array to Data with JSONEncoder, then call UserDefaults.standard.set(_:forKey:) with a versioned key such as habits.v1. On launch, data(forKey:) retrieves the bytes and JSONDecoder rebuilds the models. Missing data produces an empty tracker, while invalid data can fall back safely.

This approach still has limits. It is unsuitable for thousands of detailed logs, confidential records, or anything requiring complex queries; Core Data or SQLite would fit those cases better. A shared suiteName can support an extension, but it must be combined with the correct app-group entitlement. Synchronisation calls are unnecessary for normal app-level writes.

Build the interface with UIKit

The interface is built programmatically with UIKit so every view has a matching Swift counterpart. A UITableView presents the habits, a custom UITableViewCell shows the title and streak, and a button completes the selected row. Auto Layout keeps the controls aligned on smaller iPhones and in landscape.

UIKit provides enough primitives for the screen. A desktop interface walkthrough is a useful reminder that a data table alone does not create a friendly interface, even when the underlying controls differ. The tracker screen stays compact with four reusable pieces:

  • A table view for the user’s saved habits.
  • A custom cell with a title, streak count, and completion button.
  • A header stack with the current date, progress, and an add button.
  • An empty-state label that explains how to add the first habit.

The layout uses Dynamic Type, clear button labels, and accessibility traits instead of relying on colour alone. A completed row can use a tick, a strike-through title, and updated text, so its state remains clear for users with colour-vision differences. VoiceOver should announce the habit name and its next action before the control is activated.

Connect daily check-ins to stored data

The add habit control presents an alert with a text field. After checking that the title is not empty, the controller creates a Habit, appends it to the collection, and saves the updated array. Each completion button then sends its habit ID back through a closure. The controller checks whether today’s normalised date is already in completedDays, inserts or removes it, updates the streak, and persists the result.

Keeping those mutations in one place prevents the cell and model from disagreeing about what has been completed. The cell receives its displayed state from the model rather than maintaining a second copy. This also makes a button’s accessibility label easy to control: it can change from “Mark as complete” to “Mark as incomplete” after the action.

A diffable data source fits the list well. After changing the model, I apply a new snapshot to give the table stable identifiers and animations. If the data source is simpler, reloadData() still works, but the visual jump should be checked. A quiet refresh is better than an animation that suggests the habit itself has changed identity.

The app lifecycle creates another edge case. A view controller can disappear while the app is backgrounded, and the calendar date may cross midnight while it is away. viewWillAppear can reload stored habits, while the scene’s sceneWillEnterForeground callback provides a better refresh point when returning from the background. The streak calculation should always use the user’s current local day, not the date when the habit was created.

Test the persistence loop

Testing persistence is quicker when each layer has a visible contract. I use a short checklist that covers both a normal launch and the moments where state is most likely to drift:

  • Create two habits with distinct titles.
  • Mark one complete and leave the other pending.
  • Terminate and relaunch the app to confirm both remain.
  • Cross midnight and verify the new day starts unfinished.

Failed decoding needs a deliberate fallback too. Instead of force unwrapping saved data, the loader can record the problem, return an empty state, and offer a safe reset. Empty arrays and corrupted values should produce different results internally, even if the user sees one friendly screen. Versioned keys also leave room for a migration before the storage format changes.

The Australian market is crowded with free habit and wellbeing apps, so a small tracker can compete through a narrow routine rather than a large feature set. A local-first product also avoids forcing account creation. If a future version adds coaching or reminders, Australian pricing should be shown clearly in AUD, with renewal terms stated before a subscription begins.

Carry lessons into the next UIKit project

The project reinforced two useful rules for junior iOS development. First, persistence belongs in the product design, not in a final patch after the interface works. Second, a small complete feature teaches more than a large collection of disconnected screens. The habit list, check-in action, and local storage formed one system that could be tested from end to end.

UIKit still rewards careful boundaries. View controllers can coordinate actions, cells can display state, and a dedicated persistence helper can own encoding and retrieval. That separation makes future changes safer, whether the next step is a widget, a richer chart, or a move from local data to CloudKit. Further iOS development notes are available through my iOS learning site.

The most reusable outcome was learning how an app’s short lifecycle and long-term memory meet at launch. The practical takeaway is to build one complete habit loop—create, complete, persist, and relaunch—and make the interface, model, and local storage agree on the same record before adding another feature.

Updated: