Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Weather App Dark Sky API Client Updating the UI From a Background Thread

Stephen Wall
PLUS
Stephen Wall
Courses Plus Student 27,294 Points

Why did you place the DispatchQueue.main.async in the DarkSkyAPIClient class?

Just curious why the call to the main thread was put into the client class and not just in the function that calls only UI updates, displayWeather():

func displayWeather(using viewModel: CurrentWeatherViewModel) {
        DispatchQueue.main.async {
            self.currentTemperatureLabel.text = viewModel.temperature
            self.currentHumidityLabel.text = viewModel.humidity
            self.currentPrecipitationLabel.text = viewModel.precipitationProbability
            self.currentWeatherIcon.image = viewModel.icon
            self.currentSummaryLabel.text = viewModel.summary
        }
    }

Seems to me that only the code that actually changes the UI should be on the main thread. Does it matter?

1 Answer

Caleb Kleveter
MOD
Caleb Kleveter
Treehouse Moderator 37,862 Points

If you think about it, that code will always have to be called on the main thread because it only updates the UI, nothing else. You could have the main thread closure go around the method call, but that would have to happen every time you call the method, so it saves you some code and debugging time when you forget to call it in the main thread by placing the callback in the method.