iPhones record steps all day, and HealthKit is how an app reads them with the user's permission. This project reads the last seven days of steps, shows today's number with a progress bar toward a goal, and draws a bar chart with Swift Charts. Health data is private, so the lesson also shows how permission works and what your app can and cannot learn about the user's answer.
The Simulator has no step data, so the project uses the same trick as the AI chat: a protocol with two implementations. HealthKitService talks to the real HealthKit on a device, and FakeHealthService returns made-up numbers so you can build and test the whole screen on any Mac.
Concepts in this project
- HealthKit capability and privacy text: add the HealthKit capability and a usage description, or the app will crash when it asks for access.
- Read authorisation:
requestAuthorization(toShare:read:). For read access, iOS does not tell the app if the user said no, so a denied user simply sees zeros. - HKStatisticsCollectionQuery: asks for one total per day over a date range.
- Continuations:
withCheckedThrowingContinuationwraps a callback API so you can useawait. - Swift Charts:
BarMarkfor each day andRuleMarkfor the goal line. - A fake service: lets you build and test without a device.
Create the project
- In Xcode choose File > New > Project > iOS > App. Set Interface to SwiftUI, Language to Swift, and Testing System to Swift Testing. Set the minimum deployment to iOS 17, because the code uses @Observable. Name the product StepTracker.
- Select the app target, open Signing & Capabilities, press + Capability and add HealthKit.
- In the Info tab add Privacy - Health Share Usage Description with a plain sentence about why you read steps (see the capabilities note below).
- Delete the default ContentView.swift and the default @main file, then add the files below.
StepTracker/
FitnessApp.swift @main
HealthService.swift protocol, HealthKit and fake services
StepMath.swift progress, average, goal days
FitnessViewModel.swift loading state
FitnessView.swift summary and chart
StepTrackerTests/
FitnessTests.swift
The code
`HealthService.swift`
import Foundation
import HealthKit
struct DaySteps: Identifiable, Equatable {
let date: Date
let steps: Int
var id: Date { date }
}
enum HealthError: LocalizedError {
case unavailable
var errorDescription: String? {
"Health data is not available on this device."
}
}
protocol HealthService {
func requestAccess() async throws
func lastDays(_ count: Int) async throws -> [DaySteps]
}
// The real service. It needs the HealthKit capability and the usage text from the lesson.
final class HealthKitService: HealthService {
private let store = HKHealthStore()
private let stepType = HKQuantityType(.stepCount)
func requestAccess() async throws {
guard HKHealthStore.isHealthDataAvailable() else { throw HealthError.unavailable }
// For read access iOS never tells the app whether the user said yes or no.
try await store.requestAuthorization(toShare: [], read: [stepType])
}
func lastDays(_ count: Int) async throws -> [DaySteps] {
let calendar = Calendar.current
let today = calendar.startOfDay(for: .now)
guard let start = calendar.date(byAdding: .day, value: -(count - 1), to: today),
let end = calendar.date(byAdding: .day, value: 1, to: today) else { return [] }
let predicate = HKQuery.predicateForSamples(withStart: start, end: end)
return try await withCheckedThrowingContinuation { continuation in
let query = HKStatisticsCollectionQuery(
quantityType: stepType,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: start,
intervalComponents: DateComponents(day: 1)
)
query.initialResultsHandler = { _, results, error in
if let error {
continuation.resume(throwing: error)
return
}
var days: [DaySteps] = []
results?.enumerateStatistics(from: start, to: end) { statistics, _ in
let value = statistics.sumQuantity()?.doubleValue(for: .count()) ?? 0
days.append(DaySteps(date: statistics.startDate, steps: Int(value)))
}
continuation.resume(returning: days)
}
store.execute(query)
}
}
}
// Made-up numbers for the Simulator, which has no step data, and for tests.
struct FakeHealthService: HealthService {
func requestAccess() async throws {}
func lastDays(_ count: Int) async throws -> [DaySteps] {
let calendar = Calendar.current
let sample = [4200, 8800, 6100, 10250, 7300, 9100, 5400]
return (0..<count).map { offset in
let day = calendar.date(byAdding: .day, value: -(count - 1 - offset), to: calendar.startOfDay(for: .now)) ?? .now
return DaySteps(date: day, steps: sample[offset % sample.count])
}
}
}
`StepMath.swift`
import Foundation
enum StepMath {
// 0...1 for the progress bar. Never above 1, never below 0.
static func progress(steps: Int, goal: Int) -> Double {
guard goal > 0 else { return 0 }
return min(max(Double(steps) / Double(goal), 0), 1)
}
static func average(_ days: [DaySteps]) -> Int {
guard !days.isEmpty else { return 0 }
return days.reduce(0) { $0 + $1.steps } / days.count
}
static func daysMetGoal(_ days: [DaySteps], goal: Int) -> Int {
days.filter { $0.steps >= goal }.count
}
}
`FitnessViewModel.swift`
import Foundation
import Observation
@Observable
@MainActor
final class FitnessViewModel {
enum State {
case loading
case ready([DaySteps])
case failed(String)
}
let goal = 8000
private(set) var state: State = .loading
private let service: HealthService
init(service: HealthService) {
self.service = service
}
func load() async {
state = .loading
do {
try await service.requestAccess()
state = .ready(try await service.lastDays(7))
} catch {
state = .failed(error.localizedDescription)
}
}
var today: DaySteps? {
if case .ready(let days) = state { return days.last }
return nil
}
}
`FitnessView.swift`
import SwiftUI
import Charts
struct FitnessView: View {
@State private var model: FitnessViewModel
init(service: HealthService) {
_model = State(initialValue: FitnessViewModel(service: service))
}
var body: some View {
NavigationStack {
Group {
switch model.state {
case .loading:
ProgressView()
case .failed(let message):
VStack(spacing: 12) {
Text(message)
Button("Try again") { Task { await model.load() } }
.buttonStyle(.borderedProminent)
}
case .ready(let days):
ScrollView {
VStack(alignment: .leading, spacing: 16) {
summary(days)
chart(days)
Text("Met the goal on \(StepMath.daysMetGoal(days, goal: model.goal)) of \(days.count) days. Average: \(StepMath.average(days)) steps.")
.font(.callout)
.foregroundStyle(.secondary)
}
.padding()
}
}
}
.navigationTitle("Steps")
}
.task { await model.load() }
}
private func summary(_ days: [DaySteps]) -> some View {
let steps = days.last?.steps ?? 0
return VStack(alignment: .leading, spacing: 6) {
Text("Today").font(.caption).foregroundStyle(.secondary)
Text("\(steps)").font(.system(size: 52, weight: .bold))
ProgressView(value: StepMath.progress(steps: steps, goal: model.goal))
Text("Goal: \(model.goal) steps").font(.caption)
}
}
private func chart(_ days: [DaySteps]) -> some View {
Chart {
ForEach(days) { day in
BarMark(
x: .value("Day", day.date, unit: .day),
y: .value("Steps", day.steps)
)
.foregroundStyle(day.steps >= model.goal ? Color.green : Color.blue)
}
RuleMark(y: .value("Goal", model.goal))
.lineStyle(StrokeStyle(lineWidth: 1, dash: [4]))
.foregroundStyle(.orange)
}
.frame(height: 220)
.accessibilityLabel("Bar chart of steps for the last seven days")
}
}
`FitnessApp.swift`
import SwiftUI
@main
struct FitnessApp: App {
var body: some Scene {
WindowGroup {
// Use FakeHealthService() in the Simulator, which has no step data.
FitnessView(service: HealthKitService())
}
}
}
`FitnessTests.swift (in the tests target)`
import Testing
import Foundation
@testable import StepTracker
struct FitnessTests {
private func days(_ steps: [Int]) -> [DaySteps] {
steps.enumerated().map { DaySteps(date: Date(timeIntervalSince1970: Double($0.offset) * 86_400), steps: $0.element) }
}
@Test func progressIsClamped() {
#expect(StepMath.progress(steps: 4000, goal: 8000) == 0.5)
#expect(StepMath.progress(steps: 20000, goal: 8000) == 1)
#expect(StepMath.progress(steps: 100, goal: 0) == 0)
}
@Test func averageAndGoalDays() {
let week = days([4000, 8000, 12000])
#expect(StepMath.average(week) == 8000)
#expect(StepMath.daysMetGoal(week, goal: 8000) == 2)
}
@Test func emptyListIsSafe() {
#expect(StepMath.average([]) == 0)
}
@MainActor
@Test func fakeServiceFillsTheChart() async {
let model = FitnessViewModel(service: FakeHealthService())
await model.load()
#expect(model.today != nil)
}
}
`Capabilities and Info.plist notes for the projects that need them`
Info.plist keys and capabilities used by projects 8 to 10
(In Xcode: select the project, pick the app target, then Info and Signing & Capabilities.)
Project 8, Fitness (StepTracker)
Capability: HealthKit
Info.plist: Privacy - Health Share Usage Description
"Steps are read to show your daily progress. They never leave your phone."
Project 9, Music (MusicPlayer)
Capability: Background Modes, tick "Audio, AirPlay, and Picture in Picture"
Project 10, QR scanner (QRScanner)
Info.plist: Privacy - Camera Usage Description
"The camera is used to scan QR codes. Pictures are not saved or sent anywhere."
Needs a real iPhone (the Simulator has no camera).
The other projects need no special capability.
Walkthrough
HealthService is a protocol with two functions. The view model only knows the protocol, so it works the same with the real or the fake service. HealthKitService.requestAccess first checks isHealthDataAvailable, because some devices, such as certain iPads, have no Health data. Then it asks to read step counts. Apple deliberately hides whether the user allowed it, to protect privacy.
lastDays works out a start date seven days back and an end date after today, using Calendar arithmetic, and builds a predicate for that range. HKStatisticsCollectionQuery with .cumulativeSum and a one-day interval returns one total per day. HealthKit uses callbacks, so the code wraps the query in a continuation: initialResultsHandler either throws the error or returns the list of days. The handler uses enumerateStatistics to turn each day's statistics into a DaySteps.
StepMath holds the three small calculations as pure functions: a progress value that is clamped between 0 and 1, an average and the number of days that met the goal. Keeping them out of the view lets the tests check the edge cases, such as a goal of zero, which would otherwise divide by zero.
The view model has a State enum and a load function that requests access and then fetches. If anything throws, it shows the error with a Try again button. FitnessView receives the service in its initialiser, so the app decides which one to use. In the Simulator, pass FakeHealthService().
In the chart, each BarMark uses the date with unit: .day, so the axis shows days, and the colour is green when the goal is met. The RuleMark draws a dashed orange line at the goal. The accessibilityLabel gives VoiceOver users a description of the chart, which is an easy accessibility win.
How it works
- On appear the view calls
load. The service asks for access and returns seven days of steps. - The summary shows the last day as today, with a progress bar toward 8,000 steps.
- The chart draws seven bars and the goal line. Green bars met the goal.
- A line of text reports how many days met the goal and the average.
Expected output
On a real iPhone, a Health permission sheet appears first, asking to read Steps. After you allow it, the screen shows today's step count in large type, a progress bar, "Goal: 8000 steps" and a bar chart for the last seven days with a dashed goal line. If you walk and reopen the app, today's number rises. With FakeHealthService in the Simulator, you see the numbers 4200, 8800 and so on, with the days that reach 8000 in green. The four tests pass.
Your task
- Run with the fake service in the Simulator, then on a real iPhone with HealthKit.
- Add a goal setting stored with @AppStorage.
- Add distance walked using the distance walking and running type.
- Write the steps for a test user by adding sample data in the Health app on a device.
How to check it worked
- The app asks permission before reading steps.
- The chart shows seven days with a goal line.
- You can explain why the app cannot know if the user denied access.
Next, try the same idea on another platform with the Android Development with Kotlin course, or go deeper on iOS with the Advanced iOS Development course.