Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 46 Β· Projects

Project: A Weather App with Networking

Build a SwiftUI weather app: decode a forecast, model load states, search cities, write a view model and handle error and empty states. Runs against a fake API here.

A weather app is the standard networking exercise: ask a server for data, decode JSON, show a spinner, then show a result or an error. The tricky part is not the request itself. It is everything around it: what the screen shows while waiting, what it shows when the city is unknown, and how to stop an old answer from overwriting a newer one.

In this project you will build the app's brain in layers: forecast models, a service protocol, a view model with explicit load states, and search. A real weather service needs the network and usually an API key, which cannot run here, so the code on this page talks to a fake service that returns canned JSON. The SwiftUI views are read-only. The design is the same one you would use with a real service; you only swap the service. It builds on Codable and JSON, URLSession and async/await and MVVM.

One screen, four states

Idle Nothing searched yet.
Loading Show a spinner.
Loaded Show the forecast.
Failed Explain and offer retry.

An enum makes impossible combinations impossible.

1 / 2

Step 1: the forecast models

Imagine the service answers with JSON like this (invented for this project):

JSON
{
  "city": "Lisbon",
  "current": { "temp_c": 21.5, "summary": "Sunny" },
  "days": [
    { "day": "Mon", "high_c": 24, "low_c": 15 },
    { "day": "Tue", "high_c": 22, "low_c": 14 }
  ]
}

The keys use snake_case. Swift properties use camelCase, and JSONDecoder converts for you with keyDecodingStrategy = .convertFromSnakeCase, so you rarely need a CodingKeys enum.

Swift
// read-only: Models/Forecast.swift
import Foundation

struct Forecast: Decodable, Equatable {
    struct Current: Decodable, Equatable {
        let tempC: Double
        let summary: String
    }
    struct Day: Decodable, Equatable, Identifiable {
        let day: String
        let highC: Double
        let lowC: Double
        var id: String { day }
    }

    let city: String
    let current: Current
    let days: [Day]
}

Step 2: the service behind a protocol

The view model should not know whether data comes from the network, a file or a test. Hide that behind a protocol with one async throws method. The real implementation would call URLSession; the fake returns strings and can be told to fail.

Swift
// read-only: the real service (needs a network and an API endpoint)
struct LiveWeatherService: WeatherService {
    func forecast(for city: String) async throws -> Forecast {
        var components = URLComponents(string: "https://api.example.com/forecast")!
        components.queryItems = [URLQueryItem(name: "city", value: city)]
        let (data, response) = try await URLSession.shared.data(from: components.url!)
        guard let http = response as? HTTPURLResponse else { throw WeatherError.badResponse }
        switch http.statusCode {
        case 200: break
        case 404: throw WeatherError.cityNotFound(city)
        default: throw WeatherError.server(http.statusCode)
        }
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        return try decoder.decode(Forecast.self, from: data)
    }
}

Use URLComponents with URLQueryItem rather than gluing strings together, so a city such as "SΓ£o Paulo" is percent-encoded correctly. The runnable version below keeps the same protocol, decoding and errors, and replaces only the transport.

Swift Models, service protocol and fake API

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Notice that one malformed reply (Broken) becomes a typed decoding error rather than a crash, and that the status code is checked before decoding. A 500 response body is usually HTML or an error object, not a forecast.

Step 3: load states and the view model

The most important modeling decision: do not use isLoading, error and forecast as three separate variables. They can disagree (loading and an old error?). Use one enum so only valid situations exist.

Swift
// read-only
enum LoadState<Value> {
    case idle
    case loading
    case loaded(Value)
    case failed(String)
}

The view model then has a state, a query bound to the search field, and an async search() method. Two rules prevent subtle bugs:

  1. Ignore empty input. Do not hit the server for ""; return to idle.
  2. Latest request wins. If the user types "Lis", "Lisb", "Lisbon" quickly, three requests fly. Responses can arrive out of order. Cancel the previous task, or compare a request counter before writing the result, so a slow old answer cannot overwrite a fast new one.
Swift A view model with latest-request-wins

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The class is @MainActor, so state changes happen on the main thread, and the service protocol is Sendable so it can be called from there safely (Concurrency in iOS explains why). In the real app you would also add @Observable so views update; the stand-in leaves that macro out so it runs as a plain script, while the logic is unchanged.

Step 4: search as you type

SwiftUI offers .searchable(text:) for a native search bar, and .task(id:) to run an async job whenever a value changes, with automatic cancellation of the previous job. Together they give you debounced search in a few lines:

Swift
// read-only: Views/WeatherView.swift
import SwiftUI

struct WeatherView: View {
    @State private var model = WeatherViewModel(service: LiveWeatherService())
    @State private var query = ""

    var body: some View {
        NavigationStack {
            content
                .navigationTitle("Weather")
                .searchable(text: $query, prompt: "City")
                .task(id: query) {
                    try? await Task.sleep(for: .milliseconds(350))   // debounce
                    guard !Task.isCancelled else { return }
                    await model.search(query)
                }
        }
    }

    @ViewBuilder
    private var content: some View {
        switch model.state {
        case .idle:
            ContentUnavailableView("Search for a city", systemImage: "magnifyingglass")
        case .loading:
            ProgressView("Loading…")
        case .loaded(let forecast):
            ForecastList(forecast: forecast)
        case .failed(let message):
            ContentUnavailableView {
                Label("Something went wrong", systemImage: "exclamationmark.triangle")
            } description: {
                Text(message)
            } actions: {
                Button("Try again") { Task { await model.search(query) } }
            }
        }
    }
}

When query changes, SwiftUI cancels the running task and starts a new one, so the 350 ms sleep acts as a debounce: if the user types again within that time, the old task is cancelled before it sends a request. The switch over the state is exhaustive, so adding a new state later makes the compiler point at every screen that must handle it.

Step 5: error and empty states

Good apps explain what happened. Convert technical errors into short human messages, and decide for each whether retrying makes sense:

Swift From errors to messages

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Do not show raw error.localizedDescription for decoding problems; log the details (see Debugging Xcode Apps) and show the friendly line. Empty is not the same as error: a city with no data should show an explanation, which is what ContentUnavailableView is for.

Ideas to extend it

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Why use a single LoadState enum rather than separate isLoading, error and forecast properties?

    With three independent variables you can be loading and failed at once. One enum makes each situation exactly one case.
  2. 2. A user types quickly and responses arrive out of order. What protects the screen?

    Cancelling the previous task, or comparing a request number before writing the result, stops a slow old reply from overwriting a newer one.
  3. 3. What does .task(id: query) do when query changes?

    The task is tied to the id. A new id cancels the old task automatically and starts another.
  4. 4. Why put the service behind a protocol?

    The view model depends on the protocol only, so tests and previews can inject canned data without a network.

Summary

  • Model JSON with Decodable types and convertFromSnakeCase; check the HTTP status before decoding.
  • Hide the network behind a service protocol so a fake can replace it in previews and tests.
  • Represent the screen with one enum: idle, loading, loaded, failed.
  • Search needs "latest request wins", either by cancellation (.task(id:)) or by comparing request numbers.
  • Turn errors into human messages and decide which are worth a retry button.
  • Empty and error states are part of the design, not afterthoughts.

Next: Project: A Notes App with SwiftData