Project 6: Recipe Book App with Search and an API

iOS App Development with Swift and SwiftUI: 13 Projects · More Real-World iOS Projects · 14 min read · Updated

Search with a pause

  1. The user types in the search box.
  2. Each key cancels the previous search and starts a short wait.
  3. If the user stops typing, the service is called and returns JSON.
  4. The view shows the list, a no-results message or an error.

This project joins everything from the networking lesson: Codable models, an async service, a view model with clear states and a navigation list. The data comes from TheMealDB, a free recipe service with a public test key. The user types in a search box, the app waits a moment, and then it calls the service and shows the matching dishes. Tapping one opens the full instructions.

Two details make the app feel professional. The first is a short wait (a debounce) so the app does not send a request for every key press. The second is a screen for every state: nothing searched yet, loading, no results, an error and the list. Many beginner apps show only the happy path.

Concepts in this project

  • Codable with CodingKeys: the service names fields such as strMeal, and the model renames them to name.
  • A null list: the service answers {"meals": null} when nothing matches, so meals is optional.
  • Protocol for the service: RecipeService lets tests use a fake instead of the network.
  • State enum: idle, loading, loaded and failed make the screen simple to write.
  • Debounce with Task: cancel the old search task and start a new one after a 400 millisecond sleep.
  • ContentUnavailableView: ready-made empty and error screens in iOS 17.

Create the project

  1. 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 RecipeBook.
  2. Delete the default ContentView.swift and the default @main file, then add the files below.
RecipeBook/
  RecipeApp.swift       @main
  Recipe.swift          model + response
  RecipeService.swift   protocol + MealDBService
  RecipeViewModel.swift states and search
  RecipeViews.swift     list, detail
RecipeBookTests/
  RecipeTests.swift

The code

`Recipe.swift`

import Foundation

struct Recipe: Identifiable, Codable, Hashable {
    let id: String
    let name: String
    let category: String?
    let area: String?
    let instructions: String?
    let thumbnail: URL?

    enum CodingKeys: String, CodingKey {
        case id = "idMeal"
        case name = "strMeal"
        case category = "strCategory"
        case area = "strArea"
        case instructions = "strInstructions"
        case thumbnail = "strMealThumb"
    }
}

// The service answers {"meals": [...]} and uses null, not an empty list, when nothing matches.
struct RecipeResponse: Codable {
    let meals: [Recipe]?
}

`RecipeService.swift`

import Foundation

enum RecipeError: LocalizedError {
    case badURL
    case badStatus(Int)

    var errorDescription: String? {
        switch self {
        case .badURL: return "The search address is not valid."
        case .badStatus(let code): return "The server answered with error \(code)."
        }
    }
}

protocol RecipeService {
    func search(_ text: String) async throws -> [Recipe]
}

struct MealDBService: RecipeService {
    func search(_ text: String) async throws -> [Recipe] {
        guard var parts = URLComponents(string: "https://www.themealdb.com/api/json/v1/1/search.php") else {
            throw RecipeError.badURL
        }
        parts.queryItems = [URLQueryItem(name: "s", value: text)]
        guard let url = parts.url else { throw RecipeError.badURL }

        let (data, response) = try await URLSession.shared.data(from: url)
        if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) {
            throw RecipeError.badStatus(http.statusCode)
        }
        return try JSONDecoder().decode(RecipeResponse.self, from: data).meals ?? []
    }
}

`RecipeViewModel.swift`

import Foundation
import Observation

@Observable
@MainActor
final class RecipeViewModel {
    enum State: Equatable {
        case idle
        case loading
        case loaded([Recipe])
        case failed(String)
    }

    var query = ""
    private(set) var state: State = .idle
    private let service: RecipeService
    private var searchTask: Task<Void, Never>?

    init(service: RecipeService = MealDBService()) {
        self.service = service
    }

    // Called whenever the search text changes. Waits a moment so we do not call the server on every key.
    func queryChanged() {
        searchTask?.cancel()
        let text = query.trimmingCharacters(in: .whitespaces)
        guard text.count >= 2 else {
            state = .idle
            return
        }
        searchTask = Task {
            try? await Task.sleep(for: .milliseconds(400))
            guard !Task.isCancelled else { return }
            await load(text)
        }
    }

    func load(_ text: String) async {
        state = .loading
        do {
            let recipes = try await service.search(text)
            guard !Task.isCancelled else { return }
            state = .loaded(recipes)
        } catch is CancellationError {
            return
        } catch {
            state = .failed(error.localizedDescription)
        }
    }
}

`RecipeViews.swift`

import SwiftUI

struct RecipeListView: View {
    @State private var model = RecipeViewModel()

    var body: some View {
        NavigationStack {
            content
                .navigationTitle("Recipe Book")
                .searchable(text: $model.query, prompt: "Try chicken or pasta")
                .onChange(of: model.query) { _, _ in model.queryChanged() }
                .navigationDestination(for: Recipe.self) { RecipeDetailView(recipe: $0) }
        }
    }

    @ViewBuilder
    private var content: some View {
        switch model.state {
        case .idle:
            ContentUnavailableView("Search for a dish", systemImage: "fork.knife",
                                   description: Text("Type at least two letters."))
        case .loading:
            ProgressView("Searching...")
        case .failed(let message):
            ContentUnavailableView("Could not load recipes", systemImage: "wifi.exclamationmark",
                                   description: Text(message))
        case .loaded(let recipes):
            if recipes.isEmpty {
                ContentUnavailableView.search(text: model.query)
            } else {
                List(recipes) { recipe in
                    NavigationLink(value: recipe) {
                        HStack(spacing: 12) {
                            AsyncImage(url: recipe.thumbnail) { image in
                                image.resizable().scaledToFill()
                            } placeholder: {
                                Color.gray.opacity(0.2)
                            }
                            .frame(width: 56, height: 56)
                            .clipShape(RoundedRectangle(cornerRadius: 8))
                            VStack(alignment: .leading) {
                                Text(recipe.name).font(.headline)
                                Text([recipe.category, recipe.area].compactMap { $0 }.joined(separator: " · "))
                                    .font(.caption)
                                    .foregroundStyle(.secondary)
                            }
                        }
                    }
                }
            }
        }
    }
}

struct RecipeDetailView: View {
    let recipe: Recipe

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 12) {
                AsyncImage(url: recipe.thumbnail) { image in
                    image.resizable().scaledToFit()
                } placeholder: {
                    ProgressView()
                }
                .frame(maxWidth: .infinity)
                .clipShape(RoundedRectangle(cornerRadius: 12))
                Text("Instructions").font(.title3.bold())
                Text(recipe.instructions ?? "No instructions were provided.")
            }
            .padding()
        }
        .navigationTitle(recipe.name)
        .navigationBarTitleDisplayMode(.inline)
    }
}

`RecipeApp.swift`

import SwiftUI

@main
struct RecipeApp: App {
    var body: some Scene {
        WindowGroup {
            RecipeListView()
        }
    }
}

`RecipeTests.swift (in the tests target)`

import Testing
import Foundation
@testable import RecipeBook

private struct FakeService: RecipeService {
    var result: Result<[Recipe], Error>
    func search(_ text: String) async throws -> [Recipe] { try result.get() }
}

private struct Boom: Error {}

@MainActor
struct RecipeTests {
    private let sample = Recipe(id: "1", name: "Pasta", category: "Pasta", area: "Italian",
                                instructions: "Boil.", thumbnail: nil)

    @Test func decodesTheServiceJSON() throws {
        let json = """
        {"meals":[{"idMeal":"52772","strMeal":"Teriyaki Chicken","strCategory":"Chicken","strArea":"Japanese","strInstructions":"Cook.","strMealThumb":"https://example.com/a.jpg"}]}
        """
        let decoded = try JSONDecoder().decode(RecipeResponse.self, from: Data(json.utf8))
        #expect(decoded.meals?.first?.name == "Teriyaki Chicken")
    }

    @Test func nullMealsDecodesToNil() throws {
        let decoded = try JSONDecoder().decode(RecipeResponse.self, from: Data(#"{"meals":null}"#.utf8))
        #expect(decoded.meals == nil)
    }

    @Test func successShowsRecipes() async {
        let model = RecipeViewModel(service: FakeService(result: .success([sample])))
        await model.load("pasta")
        #expect(model.state == .loaded([sample]))
    }

    @Test func failureShowsMessage() async {
        let model = RecipeViewModel(service: FakeService(result: .failure(Boom())))
        await model.load("pasta")
        if case .failed = model.state {
            #expect(Bool(true))
        } else {
            Issue.record("Expected the failed state")
        }
    }
}

Walkthrough

Recipe uses CodingKeys to connect the service's field names to clean Swift names. Most fields are optional because the service does not always fill them. RecipeResponse wraps the top-level object, with meals as an optional array. Decoding the null case into nil, then using ?? [], turns "no results" into an empty list.

MealDBService builds the address with URLComponents and URLQueryItem, which encodes the search text safely. Typing "mac & cheese" works because the ampersand is escaped for you. It then checks the status code before decoding, as in lesson 11.

The view model is marked @MainActor, so changes to state happen on the main thread. queryChanged is the debounce: it cancels the previous task, ignores searches shorter than two letters, and starts a new task that sleeps for 400 milliseconds. If the user types another letter during that time, this task is cancelled and never calls the service. load handles the call and catches errors into the failed state.

In the view, a switch on model.state chooses what to show. searchable adds the search field, and onChange(of:) calls queryChanged. navigationDestination(for: Recipe.self) connects a tapped row to the detail screen. AsyncImage loads the picture and shows a grey placeholder meanwhile.

The tests do not use the network. They decode sample JSON, including the null case, and run the view model with a fake service that returns either a recipe or an error. Tests that depend on a real server fail when the server is slow or offline, so they are worse than useless.

How it works

  • The user types. onChange calls queryChanged, which waits 400 milliseconds before searching.
  • load sets the loading state, calls the service and sets loaded or failed.
  • The view draws the right screen for each state.
  • Tapping a row pushes the detail view with the whole recipe.

Expected output

On launch the screen says "Search for a dish". Type "chicken": a spinner shows briefly and then a list of dishes with small pictures, categories and countries appears. Type a nonsense word: "No Results for ..." appears. Tap a dish: a detail screen shows a large picture and the instructions. Turn on Airplane Mode and search again: the screen shows "Could not load recipes" with a message. The four tests pass.

Your task

  1. Build the app and search for pasta, chicken and a nonsense word.
  2. Open the service address in a browser to compare the JSON with the model.
  3. Add a favourites list saved with SwiftData.
  4. Show the ingredients by combining the numbered fields the service provides.

How to check it worked

  • Every state has its own screen.
  • The app does not search on every key press.
  • Tests run with no network.

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.

Frequently asked questions

What is a debounce?

A short delay that restarts on every new input, so the work only happens when the user pauses. It saves requests and battery.

Why is meals optional?

The service sends null instead of an empty list when nothing matches. An optional lets decoding succeed.

Can this service change or disappear?

Yes. It is a free public service. If it stops working, change the address and models to another recipe API.