With the sample code below I have made a test to understand the async and await mechanism in Swift. The sequence of processes is achieved. My test prints to the console do appear in the intended sequence (step 1-4). However, what puzzles me is that the test messages, which shall appear on the UI, do not show up in the intended sequence. Both messages (Message1 and Message2) appear together at the end of the entire process after step 4. So why does Message1 not appear right after step 1 as coded?
import UIKit
class ViewController: UIViewController {
var testasyncDone = false
@IBOutlet weak var MyButton2: UIButton!
@IBOutlet weak var Message1: UITextField!
@IBOutlet weak var Message2: UITextField!
@IBAction func MyButton2pressed(_ sender: UIButton) {
print("MyButton Pressed step 1")
// This first message shall appear right after the button
// is pressed
Message1.text = "In Button action - start"
// The async task is defined and started
testasyncDone = false
Task.detached {
await self.testasync()
print("MyButton Pressed step 4")
}
// The intention of the next lines is to hold the
// processing of the main thread until the async task is
// completed.
var count = 0
repeat {
count = count + 1
usleep(100000)
print (count)
} while testasyncDone == false && count < 100
// After the async task is done, the second message shall show up
Message2.text = "In Button action - end"
}
func testasync() async {
print("in testasync step 2")
sleep(2)
print("in testasync step 3")
testasyncDone = true
}
}