今日已更新 315 条资讯 | 累计 28627 条内容
关于我们

Understanding MVVM by Building a Simple Weather App with SwiftUI

GeraldCO 2026年08月06日 11:53 2 次阅读 来源:Dev.to

MVVM with swiftUI When learning SwiftUI, one of the first architectural patterns you'll encounter is MVVM (Model-View-ViewModel). In this tutorial, we'll build a simple weather application that consumes the OpenWeather API while applying MVVM, dependency injection, and protocol-oriented programming. By the end, you'll understand not only how to structure the project, but also why each layer exists. This is the link for the OpenWeather API https://openweathermap.org/api . What you'll learn By the end of this tutorial you'll know how to: Structure a SwiftUI project using MVVM. Consume a REST API using async/await. Apply dependency injection using protocols. Display loading and error states. Keep Views focused only on UI. This is how the data flow looks. User taps "Search" │ ▼ ┌──────────────┐ │ ContentView │ └──────┬───────┘ │ await fetchWeather() │ ▼ ┌────────────────────┐ │ WeatherViewModel │ └─────────┬──────────┘ │ ▼ WeatherServiceProtocol │ ▼ ┌─────────────────┐ │ WeatherService │ └──────┬──────────┘ │ ▼ OpenWeather API Project Structure WeatherApp ├── Configuration │ └──AppConfig.swift ├── Models │ ├── Main.swift │ ├── Weather.swift │ └── WeatherResponse.swift ├── Services │ ├── WeatherService.swift │ └── WeatherServiceProtocol.swift ├── ViewModels │ └── WeatherViewModel.swift └── Views └── ContentView.swift Configuration contains application-wide constants such as the API key and base URLs. Models contains the data structures used to decode the API response. Services is responsible for networking and fetching data. ViewModels contains the presentation logic and exposes data to the UI. Views contains the SwiftUI interface. On the AppConfig file, we are going to keep static info, just like the base URL, API key, etc struct AppConfig { static let apiKey = "YOUR API KEY" static let baseGeoCodingAPIURL = "https://api.openweathermap.org/geo/1.0/direct?q=" static let baseURL = "https://api.openweathermap.org/data/2.5/weather?&units=metric&lat=" } Designing the UI Befo

本文内容来源于互联网,版权归原作者所有
查看原文