'@Published var from ObservableObject not updating SwiftUI View

My code is printing the value that i want in the console, however the view isn't updating. Ive tried @StateObject as well and still no luck. Checked multiple similar questions and tried their solutions.

My ObservableObject with the @Published var city

class WeatherManager: ObservableObject {
  @Published var city = "Weatha"
  
  let weatherURL = *my url with key*
  
  func fetchWeather(lat: CLLocationDegrees, lon: CLLocationDegrees) {
    let urlString = "\(weatherURL)&lat=\(lat)&lon=\(lon)"
    print(urlString)
    requestData(from: urlString)
  }
  
  func requestData(from url: String) {
    guard let url = URL(string: url) else {
      print("No URL Found")
      return
    }
    URLSession.shared.dataTask(with: url) { data, response, error in
      do {
        if let safeData = try JSONDecoder().decode(WeatherModel?.self, from: data!) {
          let weather = safeData
          DispatchQueue.main.async {
            self.city = weather.name
            print("Success")
            print(weather.name)
          }
        }
      } catch {
        print("Failed fetching data, \(error)")
      }
    }
    .resume()
  }
}

My view that i'm trying to update with weathermanager.city

struct CenterWeatherView: View {
  @StateObject private var locationManager = LocationManager()
  @ObservedObject var weatherManager = WeatherManager()
  
  var body: some View {
    VStack {
      Text(weatherManager.city)
        .kerning(1.0)
        .fontWeight(.bold)
        .foregroundColor(Color("TextColor"))
        .multilineTextAlignment(.center)
        .lineSpacing(4)
        .font(.title)
    }
  }
}

Heres where i make the request if it matters

struct TopToolBar: View {
  
  @StateObject private var locationManager = LocationManager()
  @ObservedObject var weatherManager = WeatherManager()
  var body: some View {
        Button {
          locationManager.manager.requestWhenInUseAuthorization()
          print(locationManager.lastLocation ?? 0)
          weatherManager.fetchWeather(lat: locationManager.lastLocation!.latitude, lon: locationManager.lastLocation!.longitude)
        } label : {
          Image(systemName: "location.circle")
            .resizable()
            .frame(width: 30, height: 30)
            .foregroundColor(Color("TextColor"))
            .padding()
      }
}

I cant get weatherManager.city to on the view, but i get it in the console. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source