Following up on my question here.
I have a method lotsOfWork() that may take some time to complete. While it runs, the user needs to wait for it to complete. I'd like to provide feedback to the user, so that (s)he sees what is going on.
I now have the following code to run my lotsOfWork() method, while allowing it to update a label showing its progress:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
DispatchQueue.global(qos: .background).async {
self.lotsOfWork()
}
}
func lotsOfWork() {
for i in 1...10 {
DispatchQueue.main.async {
self.label.text = "Working on item \(i)..."
}
sleep(1) // Simulating lots of work
}
}
}
But this also means the lotsOfWork() method will be executed in the background queue and not in main.
While lotsOfWork() is running, nothing really happens in the main queue - except from updating the label. The user cannot do anything but wait.
Question 1: Is this a substantial performance issue? Will the work need more time to complete?
Question 2: If this is an issue, is there a way to let the lotsOfWork() method run in main, while still being able to update the label.text?
I tried to use DispatchQueue.main.async and even 2 nested DispatchQueue.main.async, but this does not update the label.text.
I also tried using setNeedsDisplay() and setNeedsLayout(), but this does not change anything.
It would not be an issue to execute lotsOfWork() in main, because the user needs to wait for this work to complete before continuing. But I can't get the label.text to be updated in real time if lotsOfWork() runs in main.