DispatchGroup will solve the problems in the following three scenarios, and more.

scenarios:

you are fetching a piece of data you need before your next line of code executes, such as an apple music developer token for example. you are fetching data that needs to end up in your UI — UICollectionView, UITableView, etc — but isn’t ever getting into your UI because your views are reloading — view.reloadData — before you even get the data. you are fetching data that needs to end up in your collectionViews, tableViews, etc, and you are having to perform multiple reloads and it makes your app look choppy, giving it a bad user experience.

Ok so if none of those scenarios apply to your situation, I still highly recommend going through this article because this is a solid tool I wish I new about earlier myself and you’ll find it useful if you continue writing code because these are pretty common problems listed above.

Real quick, I recorded a video covering the same thing this article does here.

ok let’s finally get started.

This will be quick and easy. Source code is available here on GitHub

If you have a JSON formatter chrome extension it will look like this. If you don’t, it will look like plain text.

I’ll be using a small API that provides random hints. I’ve uploaded it to Heroku here. This URL will respond with a random hint.

ok so the goal here is to fetch five or so hints and display them in our UITableView. I’ve created a new Xcode project and here is my view controller and simulator.

This code simply puts a tableview on our view the size of the screen, fetches data from our endpoint on heroku four times using the fetchData function we’ve written. Each time it fetches data, it reloads the tableview on the main thread (notice line 47).