Swift/MVVM

[MVVM] MVVM 예제1

앱붕이 2021. 3. 4. 20:58
  • 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

IOS Academy

'Swift > MVVM' 카테고리의 다른 글

[MVVM] MVVM 예제2  (0) 2021.03.08
[MVVM] MVVM패턴이란?  (0) 2021.03.04