반응형
Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 | 31 |
Tags
- 순환참조
- swfitui
- Swift Concurrency
- SwiftUI
- Git
- 스레드 점유권
- REDRAW
- StateObject
- async/await
- assosiated type
- weak
- environment value
- ObservedObject
- restful api
- actor
- MainActor
- unowned
- NavigationLink
- 앱실행
- environment object
- navigationview
- git 명령어
- task 취소
- MVVM
- Access Control
- 작업 취소
- 동시성 프로그래밍
- Swift
- 격리 시스템
- rest api
Archives
- Today
- Total
Develup
[MVVM] MVVM 예제1 본문
반응형
-
Model
struct WeatherModel : Codable { let timezone : String let current : CurrentWeather } struct CurrentWeather : Codable { let temp : Float let weather : [WeatherInfo] } struct WeatherInfo : Codable { let main : String let description : String } -
ViewModel
class WeatherViewModel: ObservableObject { @Published var title : String = "-" @Published var descriptionText : String = "-" @Published var temp : String = "-" @Published var timezone : String = "-" init() { fetchWeather() } func fetchWeather() { guard let url = URL(string: "https://api.openweathermap.org/data/2.5/onecall?exclude=hourly.daily.minutely&lat=40.7128&lon=-74&units=imperial&appid=a25ffc3abde70c25f3d7f331151a9e3f") else { return } let task = URLSession.shared.dataTask(with: url) { data, _, error in guard let data = data, error == nil else{ return } do { let model = try JSONDecoder().decode(WeatherModel.self, from : data) DispatchQueue.main.async { self.title = model.current.weather.first?.main ?? "No Title" self.descriptionText = model.current.weather.first?.main ?? "No Desciption" self.temp = "\(model.current.temp)º" self.timezone = model.timezone } } catch { print("failed") } //Convert data to Model } task.resume() } } -
View
struct ContentView: View { @StateObject var viewModel = WeatherViewModel() var body: some View { NavigationView{ VStack{ Text(viewModel.timezone).font(.system(size: 32)) Text(viewModel.temp).font(.system(size: 44)) Text(viewModel.title).font(.system(size: 24)) Text(viewModel.descriptionText).font(.system(size: 24)) } .navigationTitle("Weather MVVM") } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { Group { ContentView() .preferredColorScheme(.dark) ContentView() .preferredColorScheme(.dark) } } }
완성된 화면

reference
반응형
'Swift > MVVM' 카테고리의 다른 글
| [MVVM] MVVM 예제2 (0) | 2021.03.08 |
|---|---|
| [MVVM] MVVM패턴이란? (0) | 2021.03.04 |