Dispatch
Dispatch is a framework in Foundation 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).
- Run code on a background thread
- Run code on the main thread from a background thread
- Run code in the main thread after a delay
- Practical example
- See also
- Further reading
- Notes
Run code on a background thread
Time-intensive work can run on a background thread.1
import Foundation
// Code in the main thread
DispatchQueue.global(qos: .background).async {
// Some code that takes a long time to execute
}
Run code on the main thread from a background thread
When background thread work done, the UI can be updated on the main thread.2
import Foundation
// 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
}
}
Run code in the main thread after a delay
With asyncAfter it is possible to tell the Dispatch framework to execute a block of code after a delay:
import Foundation
// Code in the main thread
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
// Code in the main thread that runs after 3 seconds
}
Practical example
import Foundation
@objc func didTapOnGenerateImageButton() {
DispatchQueue.global(qos: .background).async {
let newImage = ImageManager.generateImage() // This synchronous method could take a long time
DispatchQueue.main.async {
self.imageView = newImage // The UI can only be updated on the main thread
}
}
}