Project 2: Weather App with API and Location
What We Build
- Search a city by name (geocoding)
- Show current temperature, wind and condition icon
- Show the next 12 hours
- Loading and error screens
- Free API, no API key needed
The API: Open-Meteo offers free weather data for non-commercial use. We use
geocoding-api.open-meteo.com to find coordinates and api.open-meteo.com for the forecast. Read the provider's terms before releasing an app.
1. Models
swift
import Foundation
struct GeoResponse: Decodable { let results: [Place]? }
struct Place: Decodable, Identifiable, Hashable {
let id: Int
let name: String
let latitude: Double
let longitude: Double
let country: String?
}
struct WeatherResponse: Decodable {
let current: Current
let hourly: Hourly
struct Current: Decodable {
let temperature2m: Double
let windSpeed10m: Double
let weatherCode: Int
enum CodingKeys: String, CodingKey {
case temperature2m = "temperature_2m"
case windSpeed10m = "wind_speed_10m"
case weatherCode = "weather_code"
}
}
struct Hourly: Decodable {
let time: [String]
let temperature2m: [Double]
enum CodingKeys: String, CodingKey {
case time
case temperature2m = "temperature_2m"
}
}
}
struct HourForecast: Identifiable {
let id = UUID()
let label: String
let temperature: Double
}
func describe(code: Int) -> (text: String, symbol: String) {
switch code {
case 0: ("Clear sky", "sun.max.fill")
case 1, 2: ("Partly cloudy", "cloud.sun.fill")
case 3: ("Overcast", "cloud.fill")
case 45, 48: ("Fog", "cloud.fog.fill")
case 51...57, 61...67: ("Rain", "cloud.rain.fill")
case 71...77: ("Snow", "cloud.snow.fill")
case 80...82: ("Showers", "cloud.heavyrain.fill")
case 95...99: ("Thunderstorm", "cloud.bolt.rain.fill")
default: ("Unknown", "questionmark.circle")
}
}
2. Service
swift
struct WeatherService {
func search(city: String) async throws -> [Place] {
var c = URLComponents(string: "https://geocoding-api.open-meteo.com/v1/search")!
c.queryItems = [URLQueryItem(name: "name", value: city), URLQueryItem(name: "count", value: "5")]
let (data, _) = try await URLSession.shared.data(from: c.url!)
return try JSONDecoder().decode(GeoResponse.self, from: data).results ?? []
}
func weather(for place: Place) async throws -> WeatherResponse {
var c = URLComponents(string: "https://api.open-meteo.com/v1/forecast")!
c.queryItems = [
URLQueryItem(name: "latitude", value: "\(place.latitude)"),
URLQueryItem(name: "longitude", value: "\(place.longitude)"),
URLQueryItem(name: "current", value: "temperature_2m,wind_speed_10m,weather_code"),
URLQueryItem(name: "hourly", value: "temperature_2m"),
URLQueryItem(name: "forecast_days", value: "2"),
URLQueryItem(name: "timezone", value: "auto")
]
let (data, response) = try await URLSession.shared.data(from: c.url!)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) }
return try JSONDecoder().decode(WeatherResponse.self, from: data)
}
}
3. View Model
swift
@MainActor
@Observable
final class WeatherModel {
enum State { case idle, loading, loaded, failed(String) }
var query = ""
var places: [Place] = []
var selected: Place?
var weather: WeatherResponse?
var state: State = .idle
private let service = WeatherService()
func search() async {
let text = query.trimmingCharacters(in: .whitespaces)
guard text.count >= 2 else { places = []; return }
places = (try? await service.search(city: text)) ?? []
}
func select(_ place: Place) async {
selected = place
places = []
query = ""
state = .loading
do {
weather = try await service.weather(for: place)
state = .loaded
} catch {
state = .failed("Could not load the weather. Check your internet and try again.")
}
}
var nextHours: [HourForecast] {
guard let hourly = weather?.hourly else { return [] }
let hourFormat = DateFormatter()
hourFormat.dateFormat = "yyyy-MM-dd'T'HH:mm"
let nowIndex = hourly.time.firstIndex { (hourFormat.date(from: $0) ?? .distantPast) > .now } ?? 0
return zip(hourly.time, hourly.temperature2m).dropFirst(nowIndex).prefix(12).map {
HourForecast(label: String($0.0.suffix(5)), temperature: $0.1)
}
}
}
4. The Screen
swift
struct WeatherView: View {
@State private var model = WeatherModel()
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 20) {
if !model.places.isEmpty {
VStack(alignment: .leading) {
ForEach(model.places) { place in
Button("\(place.name), \(place.country ?? "")") {
Task { await model.select(place) }
}
.padding(.vertical, 6)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding()
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16))
}
switch model.state {
case .idle:
ContentUnavailableView("Search a city", systemImage: "magnifyingglass")
case .loading:
ProgressView().padding(.top, 60)
case .failed(let message):
ContentUnavailableView("Problem", systemImage: "exclamationmark.triangle",
description: Text(message))
case .loaded:
if let weather = model.weather, let place = model.selected {
CurrentCard(place: place, current: weather.current)
HourlyStrip(hours: model.nextHours)
}
}
}
.padding()
}
.navigationTitle("Weather")
.searchable(text: $model.query, prompt: "City name")
.task(id: model.query) {
try? await Task.sleep(for: .milliseconds(400)) // wait until typing pauses
guard !Task.isCancelled else { return }
await model.search()
}
}
}
}
struct CurrentCard: View {
let place: Place
let current: WeatherResponse.Current
var body: some View {
let info = describe(code: current.weatherCode)
VStack(spacing: 8) {
Text(place.name).font(.title2.bold())
Image(systemName: info.symbol)
.symbolRenderingMode(.multicolor)
.font(.system(size: 70))
Text("\(Int(current.temperature2m.rounded()))°").font(.system(size: 64, weight: .thin))
Text(info.text).foregroundStyle(.secondary)
Label("\(Int(current.windSpeed10m)) km/h", systemImage: "wind").font(.footnote)
}
.frame(maxWidth: .infinity)
.padding(24)
.background(.blue.gradient.opacity(0.15), in: RoundedRectangle(cornerRadius: 24))
}
}
struct HourlyStrip: View {
let hours: [HourForecast]
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 12) {
ForEach(hours) { hour in
VStack(spacing: 6) {
Text(hour.label).font(.caption)
Text("\(Int(hour.temperature.rounded()))°").font(.headline)
}
.padding(12)
.background(.regularMaterial, in: RoundedRectangle(cornerRadius: 12))
}
}
}
}
}
| Concept used | From lesson |
|---|---|
| URLSession and URLComponents | Networking |
| Decodable and CodingKeys | Codable |
| Observable view model and state enum | MVVM, loading states |
| .searchable and .task(id:) debounce | List lesson and concurrency |
Ideas: Add the device location with Core Location, save favorite cities in SwiftData, or show a daily forecast with Swift Charts.
Conclusion
You combined networking, Codable, a view model and a polished SwiftUI layout. The task(id:) trick gives you easy search-as-you-type with a small delay.
Quick Summary: Geocode a city, fetch the forecast, decode with CodingKeys, keep a state enum in an @Observable model and render cards.

