I used 'DispatchQueue.main.async' when I perform any task in main thread like Update my APP UI . When you need to run a further operation or block in main thread you can use 'OperationQueue'. Check this article to know more about OperationQueue
OperationQueue From Apple Doc
The NSOperationQueue class regulates the execution of a set of
Operation objects. After being added to a queue, an operation remains
in that queue until it is explicitly canceled or finishes executing
its task. Operations within the queue (but not yet executing) are
themselves organized according to priority levels and inter-operation
object dependencies and are executed accordingly. An application may
create multiple operation queues and submit operations to any of them.
Example :
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
calculate()
}
private func calculate() {
let queue = OperationQueue()
let blockOperation = BlockOperation {
var result = 0
for i in 1...1000000000 {
result += i
}
OperationQueue.main.addOperation {
self.activityIndicator.stopAnimating()
self.label.text = "\(result)"
self.label.isHidden = false
}
}
queue.addOperation(blockOperation)
}
}
DispatchQueue From Apple Doc
DispatchQueue manages the execution of work items. Each work item
submitted to a queue is processed on a pool of threads managed by the
system.
Example :
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error")
return
}
do {
let heroes = try JSONDecoder().decode([HeroStats].self, from: data)
DispatchQueue.main.async {
self.heroes = heroes
completed()
}
} catch let error {
print(error)
}
}.resume()