This page has moved to swiftly.dev/dispatch! The archive below will not be updated.
Dispatch is a framework that allows you to run code on different threads. By default, all code on iOS is run on the main thread (also known as the UI thread).
Time-intensive work can run on a background thread.1
// Code in the main thread
DispatchQueue.global(qos: .background).async {
// Some code that takes a long time to execute
}
When background thread work done, the UI can be updated on the main thread.2
// Code in the main thread
DispatchQueue.global(qos: .background).async {
// Some code that takes a long time to execute
DispatchQueue.main.async {
// More code in the main thread
}
}
@objc func didTapOnGenerateImageButton() {
DispatchQueue.global(qos: .background).async {
let newImage = ImageManager.generateImage() // This could take a long time
DispatchQueue.main.async {
self.imageView = newImage // The UI can only be updated on the main thread
}
}