How to run a piece of code on main thread in Swift 4

How to run a piece of code on Main Thread in Swift 4 :

While running a code on background thread, sometimes we need to push a code on to the main thread. In this tutorial, we will learn how to achieve this while developing ios apps in Swift 4 . Let’s take a look :

Why we need to run on Main Thread :

Suppose you have a table view and on clicking a cell, you will show a new ViewController . In this case, we will have to write the code of showing a new ViewController inside the following block :

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
}

But the code inside this block runs on a background thread. So, you will observe a slight delay on starting the new ViewController. That means the user will have to wait a little bit after clicking on a cell. To overcome this problem, we can push the code to start a new ViewController on Main Thread. Pushing a code to main thread is easier than you think. Just put the code inside the below block and that’s it :

DispatchQueue.main.async{
//put your code here
}

Similarly , if you want to reload a tableview, instead of using :

self.tableView?.reloadData()

you can use :

DispatchQueue.main.async{
            self.tableView.reloadData()
}

DispatchQueue processed the items submitted on a pool of threads managed by the system. ‘DispatchQueue.main’ means you want to call the code inside block ‘{}’ on main thread.

Leave a Reply