How to run code on the Main Thread with Delay in Swift

January 18, 2019

There are a lot of bugs that could be caused because code in not running on the main thread. Typically this could happen when you are making a network call and then try to up the UI and see that it will never occur! Maybe sometimes you want to delay code from happening after an X amount of time, this snippet will show you how.

DispatchQueue.main.async {
  <#code#>
}

With Delay:

DispatchQueue.main.asyncAfter(deadline: .now() + <#time#>) {
  <#code#>
}